Java generic collection cannot add list to list

Why 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(); } } 

Does not work? Just playing with generics for the purpose of training, and I expected that I could insert everything that extends the collection 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) 
+7
source share
1 answer

You declared box as a List of what extends Collection from Object . But, according to the Java compiler, it could be anything that extends Collection , i.e. List<Vector<Object>> . Therefore, it must prohibit add operations that take a generic type parameter for this reason. It cannot allow you to add an ArrayList<Object> to a List , which may be List<Vector<Object>> .

Try removing the wildcard:

 private List<Collection<Object>> box; 

This should work because you can add an ArrayList<Object> to the List from the Collection<Object> .

+13
source

All Articles