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

ary*_*naq 7 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();
}
}
Run Code Online (Sandbox Code Playgroud)

不行?为了学习的目的只是用泛型来玩,我希望我能够在那里插入任何扩展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)
Run Code Online (Sandbox Code Playgroud)

rge*_*man 13

你已经声明box是一种List延伸Collection的东西Object.但是根据Java编译器,它可以是任何扩展的东西Collection,即List<Vector<Object>>.因此,它必须禁止add采用泛型类型参数的操作.它不能让你的加入ArrayList<Object>List这可能是List<Vector<Object>>.

尝试删除通配符:

private List<Collection<Object>> box;
Run Code Online (Sandbox Code Playgroud)

这应该工作,因为你可以肯定是一个添加ArrayList<Object>ListCollection<Object>.

  • 或者,建议的`List <Collection <Object >>`已经适用于向量和arraylists,以及例如集合. (2认同)