List<? extends Number>
is best read as:
This is a list of numbers, but, covariantly.
In other words, this is a list of some concrete but unknown type. However, I do know that, whatever type it might be, at least it is either Number or some subclass thereof.
Generics is weird; once you opt into some variance, you get the restrictions to go along with that. In the case of collections, 'covariance' comes with the baggage of 'no adding'.
Try it.
g1.add(XXX);
the only thing that is legal for XXX
here? null
. That's literally it. The full and complete and exhaustive list of all you can add to this thing. certainly Number x = 5; g1.add(x);
is not going to be allowed by javac here.
By writing List<? extends a thingie>
you're saying: Yeah, I want that. I'm signing up to this restriction that I get to add absolutely nothing (other than the academic case of literal null
). In trade for handcuffing yourself, the things you can pass in for g1
is expanded considerably.
You can also opt into contravariance:
void foo(List<? super Integer> list) {
list.add(Integer.valueOf(5)); // works!
Integer x = list.get(0); // no go
}
contravariance is the opposite. add works. get doesn't work. Which in this case means: The type of the expression list.get(0)
is just.. Object
.
Now that we've covered that:
void test(List<? extends Number> g1, List<? extends Number> g2) {}
means 'my first parameter is a list of numbers, but I opt into covariance handcuffs', and 'my second parameter is a list of numbers, but I also opt into covariance handcuffs for this one too', it now makes sense why java lets you write g1 = g2
. g2 is guaranteed to be an X<Y>
, where X some concrete subclass of List
, and Y is either Number
or some subclass thereof.
This is 100% compatible, type-wise, with the notion of 'some sort of list whose type param is some covariant take on Number'. The only thing you can do a List<? extends Number>
is to invoke methods of List where any T in the signatures are 'disabled' for parameters, and replaced by the bound (Number)
for return types.
That's.. exactly what List<? extends Number>
is describing, so it's compatible.