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
posted Feb 21, 2006 03:19:00
0
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
posted Feb 21, 2006 04:39:00
0
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.
subject: Cast LinkedList to ArrayList, enjoy the class cast exception