Can't add value to the Java collection with wildcard generic type

Viewed 14386

Why this code does not compile (Parent is an interface)?

List<? extends Parent> list = ...
Parent p = factory.get();   // returns concrete implementation
list.set(0, p);   // fails here: set(int, ? extends Parent) cannot be applied to (int, Parent)
4 Answers

This is because of "capture conversion" that happens here.

Every time the compiler will see a wildcard type - it will replace that by a "capture" (seen in compiler errors as CAP#1), thus:

List<? extends Parent> list

will become List<CAP#1> where CAP#1 <: Parent, where the notation <: means subtype of Parent (also Parent <: Parent).

java-12 compiler, when you do something like below, shows this in action:

List<? extends Parent> list = new ArrayList<>();
list.add(new Parent());

Among the error message you will see:

.....
CAP#1 extends Parent from capture of ? extends Parent
.....

When you retrieve something from list, you can only assign that to a Parent. If, theoretically, java language would allow to declare this CAP#1, you could assign list.get(0) to that, but that is not allowed. Because CAP#1 is a subtype of Parent, assigning a virtual CAP#1, that list produces, to a Parent (the super type) is more that OK. It's like doing:

String s = "s";
CharSequence s = s; // assign to the super type

Now, why you can't do list.set(0, p)? Your list, remember, is of type CAP#1 and you are trying to add a Parent to a List<CAP#1>; that is you are trying to add super type to a List of subtypes, that can't work.

Related