Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics wildcards: Why does this not compile?

Tags:

java

class Demo {
    <T> void gTee(List<List<T>> tl) {
        tee(tl);
    }

    void tee(List<List<?>> tl) {
    }
}

JDK 8 says

incompatible types: java.util.List<java.util.List<T>> cannot be converted to java.util.List<java.util.List<?>>

How come? I was of the opinion that the ? wildcard stands for any type.

like image 747
Pfiver Avatar asked Feb 04 '23 08:02

Pfiver


1 Answers

This is due to this behaviour of Java generics:

Even if A and B are compatible types, SomeType<A> is not compatible with SomeType<B>

A classic example of this is trying to assign a List<Cat> to a List<Animal>.

The same thing happens here. Normally, List<T> can be assigned to List<?>. But since you are assigning List<List<T>> to List<List<?>>, you can't.

like image 128
Sweeper Avatar answered Feb 06 '23 21:02

Sweeper