【发布时间】:2013-01-06 12:31:44
【问题描述】:
有这个代码:
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扩展而来的,为什么这个类型的对象不能加入到列表中,怎么做才能加入呢?
【问题讨论】: