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?
Number object
doesn't work because the compiler doesn't know that numbers
is a list of Number
s - it only knows that it's a list of something that's a superclass of Integer
. So it might be a list of Object
s 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 Object
s 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 Integer
s, a list of Number
s or a list of Object
s, so you're only allowed to perform those actions that would work on either one of those three.
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