有谁知道为什么以下代码无法编译?add() 和 addAll() 都不能按预期工作。删除“?扩展”部分使一切正常,但是我将无法添加 Foo 的子类。
List<? extends Foo> list1 = new ArrayList<Foo>();
List<? extends Foo> list2 = new ArrayList<Foo>();
/* Won't compile */
list2.add( new Foo() ); //error 1
list1.addAll(list2); //error 2
错误1:
IntelliJ 说:
add(capture<? extends Foo>) in List cannot be applied to add(Foo)
编译器说:
cannot find symbol
symbol : method addAll(java.util.List<capture#692 of ? extends Foo>)
location: interface java.util.List<capture#128 of ? extends Foo>
错误2:
IntelliJ 给了我
addAll(java.util.Collection<? extends capture<? extends Foo>>) in List cannot be applied to addAll(java.util.List<capture<? extends Foo>>)
而编译器只是说
cannot find symbol
symbol : method addAll(java.util.List<capture#692 of ? extends Foo>)
location: interface java.util.List<capture#128 of ? extends Foo>
list1.addAll(list2);