| 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
|
 |
 |
|
|
subject: Class Cast Exception
|
|
|