Using the extends keyword in generics

I'm trying to do this -

List<? extends Integer> l = new ArrayList<Integer>();
l.add(10);

and the compiler says -

The method add(int, capture#1-of ? extends Integer) in the type List<capture#1-of ? extends Integer> is not applicable for the arguments (int)

Why can't I add an integer to the Integer list, why doesn't the compiler complain about the first line if I can't add integers?

+4
source share
1 answer

List<? extends Integer>denotes a list of an unknown type that extends Integer. Having forgotten at the moment what it Integeris final, at run time it may be a list of some subtype MyImaginaryInteger, in which case you cannot add Integer10, as this will violate type safety. Therefore, the compiler does not allow adding elements.

, List<? super Integer> , Integer. Integer 10 , , , Integer .

- List<Integer>.

+8

Source: https://habr.com/ru/post/1610103/


All Articles