This is an extension of this SO answer.
Note: This is not a duplicate of the following. Why List is not a subtype of
List<Number>
but is subtype ofList<? extends Number>
?, nor any of the questions this has been marked duplicate of. Let me explain.
The actual question was (edited to remove unnecessary code),
void wildcardsMethod(List<? super Pair<? super Number>> list) {}
//... From some method.
List<Pair<Object>> list = null;
wildcardsMethod(list);
// Error: wildcardsMethod(List<? super Pair<? super Number>>) is not applicable for the arguments (List<Pair<Object>>)
The above doesn't work.
And the answer given was similar to (if I have not misunderstood),
Pair<Object>
is a subtype ofPair<? super Number>
and so it cannot be used in place of<? super Pair<>>
.
I don't understand it in this context. I was thinking it's just a Pair
object and we should be able to use it in place of both <? extends Pair<>>
and <? super Pair<>>
. But it doesn't work in the latter.
Can someone explain why it's considered to be a subtype thus limiting it to only extends
and not super
.
EDIT:
To explain a little more, let's see why we will the method (considering PECS),
void wildcardsMethod(List<? super Pair<? super Number>> list) {}
You will be using it to add a Pair<Number>
object to the passed list
.
In this case, List<Pair<Object>>
is a valid list which can accept a Pair<Number>
object.
So, why is this not allowed?