I have a list with upper bound generics.
List<? extends Number> l = new ArrayList<>(); l.add(new Integer(3)); //ERROR l.add(new Double(3.3)); // ERROR
I don't understand the problem, because Integer and Double extend Number.
Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters. Cannot Use Casts or instanceof With Parameterized Types.
You insert elements (objects) into a Java List using its add() method. Here is an example of adding elements to a Java List using the add() method: List<String> listA = new ArrayList<>(); listA. add("element 1"); listA.
You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number>; you can achieve this by using an upper bounded wildcard.
List<? extends Number>
does not mean "a list that can hold all objects of subclasses of Number
", it means "a list parameterized to one concrete class that extends Number
". It's not the contents of the list itself you are defining, it's what the parameterized type of the actual list-object assigned to the variable can be (boy, this is harder to explain than it is to understand :) )
So, you can do:
List<? extends Number> l = new ArrayList<Integer>(); List<? extends Number> l = new ArrayList<Double>();
If you want a list that is able to hold any object of class Number or its subclasses, just do this:
List<Number> l = new ArrayList<>(); l.add(new Integer(33)); l.add(new Double(33.3d));
(The boxing of the values inserted is unnecessary, but there for clarity..)
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