javagenericsunchecked-cast

Unchecked cast from generic type to the same type


The following code generates a warning Unchecked cast: 'T' to 'U' in IntelliJ IDEA:

interface A {}
class B<T extends A, U extends A> {
    void f() {
        final T t = null;
        final U u = (U) t;
    }
}

This doesn't make sense to me, since T and U are defined as the same type. What is the problem?


Solution

  • T and U are not defined as the same type. They are both defined as extends A, which means T and U can be unrelated classes that implement the A interface. Hence the cast is not safe.

    The only safe cast you can do is to cast references of type T or U to type A. Of course you don't need such a cast. You can simply assign them to a variable of type A.