Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't add element in a upper bound generics List?

Tags:

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.

like image 777
user2693979 Avatar asked Jan 27 '14 14:01

user2693979


People also ask

What are the restrictions on generics?

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.

How do you add an element to a generic list in Java?

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.

What is upper bounded wildcards in generics?

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.


1 Answers

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..)

like image 147
Tobb Avatar answered Sep 20 '22 17:09

Tobb