Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of List of Numbers with a Bounded wildcard type

Tags:

java

generics

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?

like image 413
Farhan Shirgill Ansari Avatar asked May 28 '19 21:05

Farhan Shirgill Ansari


People also ask

What is a bounded wildcard?

A bounded wildcard is one with either an upper or a lower inheritance constraint. The bound of a wildcard can be either a class type, interface type, array type, or type variable. Upper bounds are expressed using the extends keyword and lower bounds using the super keyword.

What is bounded and unbounded wildcards in generics Java?

both bounded and unbounded wildcards provide a lot of flexibility on API design especially because Generics is not covariant and List<String> can not be used in place of List<Object>. Bounded wildcards allow you to write methods that can operate on Collection of Type as well as Collection of Type subclasses.

What happens when we use a bounded wildcard?

Use an upper-bounded wild card only when values are to be retrieved and processed and the data structure (ArrayList) won't be changed. This means that the corresponding argument of a call on m2 can be an ArrayList whose elements are of any class that is Integer or a superclass of Integer, including Number and Object.

Which is the correct way to making a list that is upper bounded by class Number?

4. Which of these is an correct way making a list that is upper bounded by class Number? Explanation: None.


1 Answers

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
like image 161
John Kugelman Avatar answered Nov 14 '22 22:11

John Kugelman