File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Cast LinkedList to ArrayList, enjoy the class cast exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Cast LinkedList to ArrayList, enjoy the class cast exception" Watch "Cast LinkedList to ArrayList, enjoy the class cast exception" New topic
Author

Cast LinkedList to ArrayList, enjoy the class cast exception

Alana Sparx
Ranch Hand

Joined: Feb 14, 2006
Posts: 121
I should know better, but here goes....
Why does this throw a class cast exception at the last line?


Both LinkedList and ArrayList implement List.
ArrayList extends AbstractList
LinkedList extends AbstractSequentialList which extends AbstractList

As ArrayList & Linked List are both of type �List�, and both share the common parent �AbstractList�, why does this fail. Is it LinkedList�s intermediate parent AbstractSequentialList spoiling the party?

Many thanks.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Because the type of list (java.util.LinkedList) is not assignable to java.util.ArrayList. That they share a common supertype hierarchy is superfluous to the issue - the list refers to a type java.util.LinkedList, and this type is not (emphasis, not) assignable to type java.util.ArrayList.

This is the plain vanilla example of failed casts and their effect, so the question really is "why do you not think it will fail?"


Tony Morris
Java Q&A (FAQ, Trivia)
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Given your discussion after the code, I thought you had meant to write this:

Not that casting to AbstractList is a *useful* thing to do, but it does demonstrate that LinkedList objects also have type AbstractList ...


There is no emoticon for what I am feeling!
Alana Sparx
Ranch Hand

Joined: Feb 14, 2006
Posts: 121
Thanx

I see the error of my ways; so obvious now I re-look at it.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Cast LinkedList to ArrayList, enjoy the class cast exception