可能是重复的问题:
Java ArrayList of ? extends Interface
代码如下:
public static class B1 {}
public static class B2 extends B1 {}
public void fun() {
List<? extends B1> l3 = new ArrayList<>();
l3.add(new B2());
}
编译错误:
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)
我猜? extends B1
的意思是任何继承自B1的类型。看起来B2类型是从B1继承而来的,那么为什么不能将这种类型的对象添加到列表中,如何使它能够被添加?
list.add(list.get(0))
和类似的组合,因为存在通配符捕获。 - Marko Topolnik