简体   繁体   中英

Use of extends keyword in 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?

List<? extends Integer> 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> 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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM