I am trying this -
List<? extends Integer> l = new ArrayList<Integer>();
l.add(10);
and 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 i am not able to add an integer to a List of Integer, Why compiler is not complaining at first line itself if i will not be able to add integers?
List<? extends Integer>
denotes a list of some unknown type that extends Integer
. Forgetting for the moment that Integer
is final
, at runtime it could be a list of some subtype MyImaginaryInteger
, in which case you cannot add the Integer
10 since that would break the type safety. That's why the compiler does not allow you to add elements.
On the other hand, List<? super Integer>
denotes a list of some unknown type that is a parent class of Integer
. In this case, adding the Integer
value 10 is OK because regardless of what that type is at runtime, Integer
is a subtype of it.
In your specific case, there's no point in having this wildcard at all -- just declare it as List<Integer>
.
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