wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes ClassCastException during iteration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException during iteration" Watch "ClassCastException during iteration" New topic

ClassCastException during iteration

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243


Why should the code below throw a ClassCastException??

While the below one works

the getData returns an Object.

SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
Rob Spoor

Joined: Oct 27, 2005
Posts: 19556

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.

How To Ask Questions How To Answer Questions
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

*instanceof* operator avoid ClassCastException and NullPointerException(some time)
I agree. Here's the link: http://aspose.com/file-tools
subject: ClassCastException during iteration
Similar Threads
java.util.List toArray() method
Generics Teaser
Generic--- ClassCastException
final array
remove the element in list while iterating through it.