File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Getting Objects from Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Getting Objects from Collections" Watch "Getting Objects from Collections" New topic
Author

Getting Objects from Collections

Alan Phillips
Ranch Hand

Joined: Aug 13, 2002
Posts: 73
I'm just wondering, in a Collection of objects, how do you get objects back out in the same type that they went in? Just like in an array where you access it by the a[10].
In the List interface, the get() method returns an Object, not the original type that went in. The Map get() does the same thing when you give it a key as a parameter.
Do you have to convert the collection to an array using toArray() to access the elements?
Thanks!
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
No. You have to cast the object when you get it out of the collection.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Also you may want to use instanceof to check that the type of object is what you are expecting before you cast it.
[ September 15, 2002: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Alan Phillips
Ranch Hand

Joined: Aug 13, 2002
Posts: 73
Great, thanks alot guys, I got it to work like this:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting Objects from Collections