Java通用集合,无法将列表添加到列表 [英] Java generic collection, cannot add list to list
问题描述
为什么如下
public class ListBox {
private随机随机= new Random
private List< ;? extends Collection< Object>>框;
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在那里,但我得到这个错误:
在类型List< capture#2-of?中的方法add(capture#2-of?extends Collection< Object& extends Collection< Object>>不适用于参数(ArrayList< Object>)
在List< capture#3-of?中的方法add(capture#3-of?extends Collection< Object& extends Collection< Object>>不适用于ListBox.addTwoForks(ListBox.java:23)
在ListBox.main(ListBox.java:28)
上的参数(ArrayList< Object>)
您已宣布 $ c>是
的
$ c>。但是根据Java编译器,它可以是扩展
Collection
的任何,即 List< Vector< Object>
。因此,它必须禁止使用通用类型参数的添加
操作。它不能让你添加 ArrayList< Object>
到列表
,可以列表< Vector< Object>>
。
尝试删除通配符:
< p $ p>
private List< Collection< Object>>框;
这应该工作,因为你可以添加 ArrayList< Object& code>到
集合< Object>
的列表
。
Why does the following
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();
}
}
Not work? Just toying around with generics for the purpose of learning and I expected that I would be able to insert anything that extends Collection in there but I get this error:
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)
You've declared box
to be a List
of something that extends Collection
of Object
. But according to the Java compiler, it could be anything that extends Collection
, i.e. List<Vector<Object>>
. So it must disallow add
operations that take the generic type parameter for this reason. It can't let you add an ArrayList<Object>
to a List
that could be List<Vector<Object>>
.
Try removing the wildcard:
private List<Collection<Object>> box;
This should work because you can certainly add an ArrayList<Object>
to a List
of Collection<Object>
.
这篇关于Java通用集合,无法将列表添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!