File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Interview Guide this week in the Jobs Discussion 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: 10033


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, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

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:
subject: ClassCastException during iteration
It's not a secret anymore!