Possible Duplicate:
Java ArrayList of ? extends Interface
There is this code:
public static class B1 {}
public static class B2 extends B1 {}
public void fun() {
List<? extends B1> l3 = new ArrayList<>();
l3.add(new B2());
}
Compile error:
java: no suitable method found for add(Main.B2)
method java.util.List.add(int,capture#1 of ? extends Main.B1) is not applicable
(actual and formal argument lists differ in length)
method java.util.List.add(capture#1 of ? extends Main.B1) is not applicable
(actual argument Main.B2 cannot be converted to capture#1 of ? extends Main.B1 by method invocation conversion)
I guess that ? extends B1 means any type that extends from B1. It seems that type B2 extends from B1, so why object of this type cannot be added to the list and how to make it so that it can be added?
No. It means “a specific, but unknown, type that extends from B1”. As the specific type is unknown, the compiler cannot enforce it, therefore operations like
adddon’t work.*See the tutorial on wildcards.
Basically, don’t use wildcards for this. You probably want this:
* Well, they do work, but only for
null(and a few other cases, see @Marko’s comment below).