| Author |
ClassCastException during iteration
|
Joe Harry
Ranch Hand
Joined: Sep 26, 2006
Posts: 8795
|
|
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: 19216
|
|
|
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
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)
|
 |
 |
|
|
subject: ClassCastException during iteration
|
|
|