Javagenerics集合,无法将列表添加到列表中
为什么如下
public class ListBox { private Random random = new Random(); private List<? extends Collection> box; public ListBox() { box = new ArrayList(); } public void addTwoForks() { int sizeOne = random.nextInt(1000); int sizeTwo = random.nextInt(1000); ArrayList one = new ArrayList(sizeOne); ArrayList two = new ArrayList(sizeTwo); box.add(one); box.add(two); } public static void main(String[] args) { new ListBox().addTwoForks(); } }
不行? 为了学习的目的只是用generics来玩,我希望我能够在那里插入任何扩展Collection的东西,但是我得到了这个错误:
The method add(capture#2-of ? extends Collection) in the type List<capture#2-of ? extends Collection> is not applicable for the arguments (ArrayList) The method add(capture#3-of ? extends Collection) in the type List<capture#3-of ? extends Collection> is not applicable for the arguments (ArrayList) at ListBox.addTwoForks(ListBox.java:23) at ListBox.main(ListBox.java:28)
您已将box
声明为扩展Object
Collection
的List
。 但是根据Java编译器,它可以是扩展Collection
任何东西 ,即List
。 因此,它必须禁止add
采用generics类型参数的操作。 它不能让您将ArrayList
添加到可能是List
。
尝试删除通配符:
private List> box;
这应该有效,因为您当然可以将ArrayList
添加到Collection
List
中。