List of List of Numbers with a Bounded wildcard type

If I have this,

Collection<? extends Number> c = new ArrayList<>();
c.add(new Integer(1)); // Compile time error

Since we don't know what the element type of c stands for, we cannot add integers to it.

But if I do like,

List<List<? extends Number>> history = new ArrayList<>();

List<Integer> integers = new ArrayList<>();
integers.add(new Integer(1));

List<Double> doubles = new ArrayList<>();
doubles.add(new Double(2));

history.add(integers); // This is allowed
history.add(doubles);  // This is allowed

Why the addition in the 2nd example is allowed?

Upvotes: 5

Views: 65

Answers (1)

John Kugelman
John Kugelman

Reputation: 361595

Collection<? extends ...>
c.add(...);

A collection with a lower bound cannot be added to.

List<List<...>> history;
history.add(...);      // Allowed

The outer list has a concrete type. The ? extends wildcard is inside the inner list, but it's irrelevant since you're adding to the outer list. I've replaced the wildcard with ... since it doesn't matter what it is when you're calling history.add().

If the outer list had a wildcard bound then adding would fail.

List<? extends List<...>> history;
history.add(...);      // NOT allowed

Upvotes: 8

Related Questions