简体   繁体   English

在泛型中使用extends关键字

[英]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 . List<? extends Integer>表示延伸一些未知类型的列表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. 忘记Integer final的那一刻,在运行时它可能是某个子类型MyImaginaryInteger的列表,在这种情况下你不能添加Integer 10,因为这会破坏类型的安全性。 That's why the compiler does not allow you to add elements. 这就是编译器不允许您添加元素的原因。

On the other hand, List<? super Integer> 另一方面, List<? super Integer> List<? super Integer> denotes a list of some unknown type that is a parent class of Integer . List<? super Integer>表示某个未知类型的列表,它是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. 在这种情况下,添加Integer值10是正常的,因为无论该类型在运行时是什么, Integer都是它的子类型。

In your specific case, there's no point in having this wildcard at all -- just declare it as List<Integer> . 在您的具体情况下,根本没有这个通配符 - 只需将其声明为List<Integer>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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