Java泛型集合,无法将列表添加到列表中

时间:2013-04-30 16:55:46

标签: java generics collections

为什么以下

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)

1 个答案:

答案 0 :(得分:13)

您已将box声明为List扩展Collection Object的内容。但根据Java编译器,它可能是任何扩展Collection,即List<Vector<Object>>。因此,它必须禁止采用泛型类型参数的add操作。它无法让ArrayList<Object>添加到List List<Vector<Object>>

尝试删除通配符:

private List<Collection<Object>> box;

这应该有效,因为您当然可以ArrayList<Object>添加List Collection<Object>