durron597 durron597 - 25 days ago 7
Java Question

Why doesn't try-catch resolve the warning in unchecked generics casts?

Consider the following MCVE:

public class MyClass {
private LinkedList<Foo> myList = new LinkedList<Foo>();

// Some irrevelant stuff which includes loading myList

public void myMethod() {
LinkedList<Foo> newList;

try {
newList = (LinkedList<Foo>) myList.clone();
} catch (ClassCastException e) {
// do something in case java screws up
}
}
}


I know that you can get rid of the warning by using
@SuppressWarnings("unchecked")
but why doesn't the
try/catch
block work? Is it a waste of time and energy to put the
try/catch
in there?

Answer

That won't work, because you are not getting a ClassCastException for this.

The erased type of the list cannot be checked at runtime.

You might get a ClassCastException when you try to get something out of the List (and that turns out not to be a Foo), but the List itself is just a LinkedList (without knowing what its element types can be).

An instance of LinkedList<Foo> looks exactly like a LinkedList<Bar> at runtime.

The reason for the warning is that the runtime system cannot guarantee that the cast you are doing is correct (it can check the LinkedList part, but not the generic type).