Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes ClassCastException and inconvertible type eror Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException and inconvertible type eror" Watch "ClassCastException and inconvertible type eror" New topic
Author

ClassCastException and inconvertible type eror

Monalisa Das
Greenhorn

Joined: May 05, 2013
Posts: 11
As given in core java api the ClassCastException is thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. ..but when we write
List lst = new ArrayList;
lst.add(1);

Iterator <String> itr = lst.iterator();
while (itr.hasNext())
{
String str = itr.next();
}
The output for this code is ClassCastException (Integer can not be casted to String )
Integer class is not parent of String class then why this exception is thrown for the code inside while loop? why not inconvertible types error was shown during compile time



Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

At compile time, the compiler doesn't know what type of objects are going to be in that List. Because you haven't told it that.

If you expected the compiler to notice that elsewhere in the code an Integer object is added to the List, then... no, the compiler doesn't look for things like that. It just looks at the declaration of the List.
Abhishk Singh
Ranch Hand

Joined: Aug 19, 2010
Posts: 43
Monalisa Das wrote:

Integer class is not parent of String class then why this exception is thrown for the code inside while loop? why not inconvertible types error was shown during compile time



Using generics can help detect such errors at compile time while working with collections.
The code using generics is as follows(for java1.7) (Although you have already used generics for the iterator) :



Here is a reference for generics.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: ClassCastException and inconvertible type eror
 
Similar Threads
ClassCastError vs. Compilation Error
Wrapper Doubt
dan exam dought 6
compiler inconvertible types vs ClassCastException
Seeking Exam Advise