Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code with generics with super does not work as expected

I have the following code :

List<? super Integer> numbers = new ArrayList<Number>();
numbers.add(new Integer(10));
Number object = numbers.get(0);  //this doesn't compile??

Object object = numbers.get(0);  //this does compile

Then if I do :

numbers.add(new Object()); //doesn't compile in contradiction to above statement

What is the reason for this?

like image 587
fastcodejava Avatar asked Dec 12 '22 15:12

fastcodejava


1 Answers

Number object doesn't work because the compiler doesn't know that numbers is a list of Numbers - it only knows that it's a list of something that's a superclass of Integer. So it might be a list of Objects for example, in which case storing the result of get in a Number variable wouldn't work. Thus the compiler doesn't allow it.

Object object is allowed because storing the result of get in an Object variable always works because you can store anything in an Object variable.

The reason that numbers.add( new Object() ) doesn't work is that you're only allowed to add Objects to List<Object>s, but numbers may very well be a List<Integer> or a List<Number> (and in fact it is the latter), so that's not allowed.

Basically you have to think of it like this: numbers may be a list of Integers, a list of Numbers or a list of Objects, so you're only allowed to perform those actions that would work on either one of those three.

like image 124
sepp2k Avatar answered Feb 12 '23 09:02

sepp2k