Number literals are of type int. Using construction <? extends Number>
you ensure, that you can pass only instances of Number
class, or any classes, that Number
inherits from (that is java.lang.Object
). If you want to add subtypes of Number
class, e.g. Integers
you should use <? super Number>
(it means: for whose Number
is a super class)
You may want to use:
List<? super Number> list = new ArrayList<>();
list.add(1); //no compile-time error
However, if you want to use elements of the collection, you may use them as instances of classes that extends Number
class.
List<? super Number> list = new ArrayList<>();
list.add(1);
list.add(2);
print(list);
List<Object> objs = new ArrayList<>();
objs.add(1);
print(objs);
List<Number> nums = new ArrayList<>();
nums.add(1);
print(nums);
}
public static void print(List<? super Number> list){ // you can pass List of instances of type Number or upper
for(Object num: list){ // but you have to refer to them as Objects (it is an upper class of Number
System.out.println(num);
}
}