durron597 durron597 - 1 year ago 63
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
but why doesn't the
block work? Is it a waste of time and energy to put the
in there?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download