This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Class Cast Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Class Cast Exception" Watch "Class Cast Exception" New topic
Author

Class Cast Exception

Rhea Rhea
Greenhorn

Joined: Jan 12, 2005
Posts: 2
Hi,
I am trying to cast a Collection to a LinkedList.Is that possible? At Compile time I am fine but at runtime my code returns a Class Cast Exception at this line :
******************************************
LinkedList acadList = new LinkedList();
acadList = (LinkedList)acadClassHome.findOpenClasses(); --ClassCastException
// findOpenClasses() returns a Collection of objects.
********************************************
The findOpenClasses is actually in an EJB which returns a Collection of objects.
What can I do to get back a LinkedList from a Collection.
Thanks,
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
If you want to convert an arbitrary Collection object into a LinkedList, you can do:
LinkedList acadList = new LinkedList( acadClassHome.findOpenClasses() );


Mike Gershman
SCJP 1.4, SCWCD in process
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
The compiler allows it because, at runtime, the returned Collection could theoretically be a LinkedList (or a TreeMap, or a Stack, or ...). You get a ClassCastException because, at runtime, it turns out the returned Collection is not a LinkedList (or a subclass of it). If you'd like to see what it is, try this:However, I suggest that you back up a step and think about what you're doing. Do you need to operate on the Collection as a LinkedList? If so, Mike's code will do that.

Or do you just need the List methods (indexed access)? If so, you can cast it to the interface List. Coding to interfaces, especially with the Collections classes, is much cleaner and allows you to switch the particular implementation (ArrayList for LinkedList) without changing your code.
Rhea Rhea
Greenhorn

Joined: Jan 12, 2005
Posts: 2
Mike and David,
I tried out Mike's Suggestion and it worked,Thanks.I do need to use the Collection as a LinkedList as the caller of the method needs a LL returned.
Thanks again.
Rhea
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Class Cast Exception
 
Similar Threads
Generic type for Iterator is also required ?
LinkedList using Generics
ClassCastException
use of List<?>
Help me .doubt in Collections