给出以下Java代码:
public void addStuff(Collection<? extends Object> aCollection) {
List<? extends Object> myList = new LinkedList<>(aCollection);
myList.addAll(aCollection);
}
构造函数调用编译,但addAll()调用无法编译。我收到以下错误:
no suitable method found for addAll(Collection<CAP#1>)
method Collection.addAll(Collection<? extends CAP#2>) is not applicable
(argument mismatch; Collection<CAP#1> cannot be converted to Collection<? extends CAP#2>)
method List.addAll(Collection<? extends CAP#2>) is not applicable
(argument mismatch; Collection<CAP#1> cannot be converted to Collection<? extends CAP#2>)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends Object from capture of ? extends Object
CAP#2 extends Object from capture of ? extends Object
即使他们有相同的签名,一个人打电话给另一个:
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
这里发生了什么?
答案 0 :(得分:3)
基本上:通配符很不稳定,Java并不认为通配符是相同的通配符。在List<? extends Object>
中,这被视为与另一个?
不同。
您可以通过命名类型来完成此工作:
public <E> void addStuff(Collection<E> aCollection) {
List<E> myList = new LinkedList<>(aCollection);
myList.addAll(aCollection);
}