可能重复:
Java ArrayList 的?扩展接口
有这个代码:
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 扩展而来的,那么为什么不能将这种类型的对象添加到列表中,以及如何使其可以添加呢?