简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM