[英]Java generic collection, cannot add list to list
為什么如下
public class ListBox {
private Random random = new Random();
private List<? extends Collection<Object>> box;
public ListBox() {
box = new ArrayList<>();
}
public void addTwoForks() {
int sizeOne = random.nextInt(1000);
int sizeTwo = random.nextInt(1000);
ArrayList<Object> one = new ArrayList<>(sizeOne);
ArrayList<Object> two = new ArrayList<>(sizeTwo);
box.add(one);
box.add(two);
}
public static void main(String[] args) {
new ListBox().addTwoForks();
}
}
不行? 為了學習的目的只是用泛型來玩,我希望我能夠在那里插入任何擴展Collection的東西,但是我得到了這個錯誤:
The method add(capture#2-of ? extends Collection<Object>) in the type List<capture#2-of ? extends Collection<Object>> is not applicable for the arguments (ArrayList<Object>)
The method add(capture#3-of ? extends Collection<Object>) in the type List<capture#3-of ? extends Collection<Object>> is not applicable for the arguments (ArrayList<Object>)
at ListBox.addTwoForks(ListBox.java:23)
at ListBox.main(ListBox.java:28)
您已將box
聲明為擴展Object
Collection
的List
。 但是根據Java編譯器,它可以是擴展Collection
任何東西 ,即List<Vector<Object>>
。 因此,它必須禁止add
采用泛型類型參數的操作。 它不能讓你添加ArrayList<Object>
一個List
,可能是List<Vector<Object>>
。
嘗試刪除通配符:
private List<Collection<Object>> box;
這應該有效,因為您當然可以將ArrayList<Object>
添加到Collection<Object>
List
中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.