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?
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.
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.
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.
4. Which of these is an correct way making a list that is upper bounded by class Number? Explanation: None.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With