File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException during iteration" Watch "ClassCastException during iteration" New topic
Author

ClassCastException during iteration

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9627
    
    2

Guys,

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
Sheriff

Joined: Oct 27, 2005
Posts: 19791
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
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