0

Consider the following Java code:

List<? super Number> list = new ArrayList<>();
Number n = new Integer(1);
Object o = new Object();
list.add(n); // works, apparently Number super Number is alright
list.add(o); // compiler error! 

But why is that the case? Since internally, type erasure makes list a list that holds Objects, why isn't it allowed to add Objects (which are superclasses of all classes, and thereby should satisfy the lower-bound wildcard) to the list?

PermGenError
  • 45,977
  • 8
  • 87
  • 106
Tilde
  • 45
  • 7

3 Answers3

2

The compiler only knows that list contains some supertype of Number (or Number itself), which may or may not be Object. So it must disallow Object because it could be List<Number>.

Here's a more thorough explanation, scroll about half way down where it talks about "? super".

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

An Object is not a Number.

A Number is an Object though.

From the accepted answer of the question this is a duplicate of:

Hence it is NOT true that you can add any supertype of Number to a List; that's simply not how bounded wildcard and capture conversion work. You don't declare a List because you may want to add an Object to it (you can't!); you do because you want to add Number objects to it (i.e. it's a "consumer" of Number), and simply a List is too restrictive.

Community
  • 1
  • 1
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
0

List<? super Number> list defines the list you can assign it to.

In other words you can assign a List<Number> or a List<Object> to it.

Afaik new ArrayList<>() would be the same as new ArrayList<Number>()

keiki
  • 3,260
  • 3
  • 30
  • 38