ClassCastException and inconvertible type eror

Monalisa Das

Greenhorn

Posts: 11

posted 3 years ago

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

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

Posts: 50

posted 3 years ago

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) :