The problem with calling a method such as add
that has a generic parameter on a class with a ? extends
wildcard is that the exact type is unknown to the compiler. It could be a List<Number>
or a List<Integer>
or a List<Double>
or a List<BigInteger>
. The compiler must preserve type safety with generics, and if it were to allow such a call, type safety would not be preserved. You shouldn't be allowed to add a Double
to a list that could be a List<Integer>
.
Such ? extends
upper-bound wildcards are useful as method parameters themselves, where the exact type doesn't matter; it just matters that it's the bound (in this case, Number
) or below.
public void foo(List<? extends Number> list) {
for (Number n : list) {
// do something with some kind of Number, don't care which