Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 832
durron597 Avatar asked Oct 23 '12 12:10

durron597


People also ask

How do I get rid of unchecked cast warning?

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.

What is unchecked warning?

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.

What is the use of @SuppressWarnings unchecked?

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


1 Answers

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

like image 200
Thilo Avatar answered Sep 25 '22 16:09

Thilo