Why can't I add an integer to this type of list, even though Integer extends Number>
List<? extends Number> numList = new ArrayList<Integer>();
Integer f = 12;
numList.add(f);
Why can't I add an integer to this type of list, even though Integer extends Number>
List<? extends Number> numList = new ArrayList<Integer>();
Integer f = 12;
numList.add(f);
Have a look at this post on the PECS principle. Relevant quote:
You want to add things to the collection.
Then the list is a consumer, so you should use aCollection<? super Thing>
.
In short, you'll want to use super
rather than extends
:
List<? super Number> numList = new ArrayList<>();
Integer f = 12;
numList.add(f);
If you want to store any kind of number, you can simply do the following:
List<Number> numList = new ArrayList<Number>();
You need to use super keyword if you want to add elements to list.
List<? super Integer> numList = new ArrayList<Integer>();
and then do
numList.add(10);
That List can be defined as List, List some other type also,In this case Compiler dont allow you to have Integer to be stored into a List: that would create problem in the type-safety features.
if you need You could use this
List<Number> numList = new ArrayList<Number>();
Integer f = 100;
numList.add(f);