Java generic extension templates: why is this not compiled?

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 did it happen? I believed that a wildcard ?denotes any type.

+4
source share
2 answers

This is due to the behavior of Java generics:

Even if Athey Bare compatible types, SomeType<A>not compatible withSomeType<B>

A classic example of this is the purpose of List<Cat>a List<Animal>.

The same thing happens here. You List<T>can usually assign List<?>. But since you are appointing List<List<T>>to List<List<?>>, you cannot.

+4
source

Oh. Holy cube. I should have known, but it didn’t occur to me:

enter image description here

https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Use-site_variance_annotations_.28wildcards.29

:

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

    void tee(List<? extends List<?>> tl) {
    }
}
+4

Source: https://habr.com/ru/post/1678278/


All Articles