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
}
}
}
@SuppressWarnings("unchecked")
try/catch
try/catch
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).