• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Cast LinkedList to ArrayList, enjoy the class cast exception

 
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?"
 
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanx

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