Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic collection, cannot add list to list

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)
like image 842
arynaq Avatar asked Apr 30 '13 16:04

arynaq


1 Answers

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>.

like image 131
rgettman Avatar answered Sep 29 '22 12:09

rgettman