Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cast LinkedList to ArrayList, enjoy the class cast exception

 
Alana Sparx
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?"
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ...
 
Alana Sparx
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx

I see the error of my ways; so obvious now I re-look at it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic