有谁知道为什么下面的代码不能编译?add()和addAll()都不能按预期工作.删除"?extends"部分会使一切正常,但之后我将无法添加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
Run Code Online (Sandbox Code Playgroud)
错误1:
IntelliJ说:
add(capture<? extends Foo>) in List cannot be applied to add(Foo)
Run Code Online (Sandbox Code Playgroud)
编译器说:
cannot find symbol
symbol : method addAll(java.util.List<capture#692 of ? extends Foo>)
location: interface java.util.List<capture#128 of ? extends Foo>
Run Code Online (Sandbox Code Playgroud)
错误2:
IntelliJ给了我
addAll(java.util.Collection<? extends capture<? extends Foo>>) in List cannot be applied to addAll(java.util.List<capture<? extends Foo>>)
Run Code Online (Sandbox Code Playgroud)
而编译器只是说
cannot find symbol
symbol …Run Code Online (Sandbox Code Playgroud)