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?
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
@SuppressWarnings("unchecked") is used when Java generics just don't let you do what you want to, and thus, you need to explicitly specify to the compiler that whatever you are doing is legal and can be executed at the time of execution.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With