Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of extends keyword in generics

Tags:

java

generics

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?

like image 345
Mohammad Adil Avatar asked Feb 09 '23 21:02

Mohammad Adil


1 Answers

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>.

like image 165
M A Avatar answered Feb 11 '23 16:02

M A