aspose 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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 9243
    
    1

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, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

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
 
Similar Threads
Generic--- ClassCastException
java.util.List toArray() method
Generics Teaser
final array
remove the element in list while iterating through it.