• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException during iteration

 
Joe Harry
Ranch Hand
Posts: 10109
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys,

Why should the code below throw a ClassCastException??


While the below one works



the getData returns an Object.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Obviously the actual contents of the List are instances of MyObject, not Long. That means that the cast to Long won't work. Just because you cast the Object to List<Long> doesn't turn every element into a Long. That's also why you got a compiler warning about this cast; the JVM cannot check at this time if the Object is really a List<Long>; all it can check is if it's a List. The warning's there because you may get unexpected ClassCastExceptions later on -- like you're getting now.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
*instanceof* operator avoid ClassCastException and NullPointerException(some time)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic