Java Generics Curiosity

I have an interface Athat implements a class B.

The following general working method works.

public static <T, U extends T> List<T> listFactory(Collection<U> source) {
    return new ArrayList<T>(source);
}

but

public static <T> List<T> listFactory(Collection<? extends T> source) {
    return new ArrayList<T>(source);
}

fails (compilation error, type mismatch) when I direct the output to

List<A> tester = listFactory(B.defaultCollectionFactory(3));

defaultCollectionFactory(int count)statically provides a collection Bs marked with a default.

Is it possible to understand why this is so? It seems that common U and wildcard do the same.

+5
source share
2 answers

, List . U extends T, A B T U .

, , T B List<B>. , , B A, List<B> List<A>. :

: <B> <A>

, List , B B (, List<Object>), .

+2

listFactory, . , T B, List<B> listFactory(Collection<? extends B> source). A, :

List<A> tester = Test.<A> listFactory(B.defaultCollectionFactory(3));
+3

All Articles