Most questions about wildcards want to know why something sensible is rejected by the compiler. My question is the opposite. Why is the following program accepted by the compiler?
void test(List<? extends Number> g1, List<? extends Number> g2)
{
g1 = g2;
}
I tried to explain this from the Java Language Specification, but I have not found the answer. I had the impression from various descriptions of Java generics and wildcards that each use of a wildcard is captured as a completely new type, but apparently not here. I have not found any nasty behavior that follows from this assignment being allowed, but it still seems "wrong".
When I face these questions, I approach this in a slightly different manner.
First of all, every single wildcard
is captured
, everywhere
, by javac
. In plain english: every time javac
"sees" a wildcard
it is going to transform that (this is almost accurate as you will see further). Specifically, let's say we have this:
List<? extends Number> list;
javac
will transform to:
List<X1> list
where X1 <: Number
, where <:
means it is a subtype of, as such : X1 is an unknown type that extends Number
. This will happen for every single occurrence. And it might be very weird, at first, in some scenarios:
public static void main(String[] args) {
List<?> l = new ArrayList<String>();
one(l);
two(l, l); // fails
}
public static <T> void one(List<T> single){
}
public static <T> void two(List<T> left, List<T> right){
}
capture conversion was applied individually to each List
, it's like this happened:
two(List<X1>, List<X2>)
Now to why is your example accepted, is far more interesting, imho. You know that capture conversion is applied, but according to the JLS
it is not applied everywhere:
If the expression name is a variable that appears "on the left hand side", its type is not subject to capture conversion.
It's like saying that only values are capture converted, not variables.
So in this case:
g1 = g2;
g1
has not been capture converted, while g2
has. It's like doing:
List<? extends Number> g1 = List<X1> (g2) // pseudo-code
We know that X1 <: Number
so, as such List<X1>
is a subtype of List<? extends Number>
, so the assignment works.
Even if you change ? extends Number
to ?
(this is not a bounded wildcard anymore), this would still work.