Consider this example:
static class Generic<E> {}
static void run() {
Generic<?> x = null;
take(x);
}
static <E> void take(final Generic<E> x) {}
In run
, the wildcard in the type of x
represents some unknown type T
. The E
parameter of the take
method can be assigned any type. The compiler infers that it's safe to assign T
to E
.
In the second example we nest the wildcard one level deeper:
static void run() {
Generic<Generic<?>> x = null;
take(x);
}
static <E> void take(final Generic<Generic<E>> x) {}
In this example the wildcard still represents some unknown type T
and the E
parameter can be assigned any type. Why does the compiler not infer that T
can be assigned to E
and allow this code to compile? Is there a principled reason for this code not compiling?
Note: changing the take
method in the second example to the below compiles:
static <E> void take(final Generic<Generic<? extends E>> x) {}
Is there an essential difference between Generic<Generic<E>>
and Generic<Generic<? extends E>>
when E
is unbounded?