2017-05-12 46 views
0

鑑於Java代碼:沒有合適的方法發現中的addAll

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); 
} 

這是怎麼回事?

回答

3

基本上:通配符是不可靠的,Java不認爲通配符是相同的通配符。在List<? extends Object>,這被認爲是另一個不同的?

你可以通過命名類型,使這項工作:

public <E> void addStuff(Collection<E> aCollection) { 
    List<E> myList = new LinkedList<>(aCollection); 
    myList.addAll(aCollection); 
} 
相關問題