为什么不能将一个对象添加到列表中?超级号码> ;? [英] Why can't one add an Object to List<? super Number>?
问题描述
考虑以下Java代码:
Consider the following Java code:
List<? super Number> list = new ArrayList<>();
Number n = new Integer(1);
Object o = new Object();
list.add(n); // works, apparently Number super Number is alright
list.add(o); // compiler error!
但是为什么会这样呢?由于在内部,类型擦除使列表成为保存对象的列表,为什么不允许将对象(所有类的超类,因此应满足下限通配符)添加到列表中?
But why is that the case? Since internally, type erasure makes list a list that holds Objects, why isn't it allowed to add Objects (which are superclasses of all classes, and thereby should satisfy the lower-bound wildcard) to the list?
推荐答案
编译器仅知道list
包含Number
的某些超类型(或Number
本身),该超类型可能是Object
,也可能不是.因此必须禁止Object
,因为它可能是List<Number>
.
The compiler only knows that list
contains some supertype of Number
(or Number
itself), which may or may not be Object
. So it must disallow Object
because it could be List<Number>
.
这是一个更详尽的解释,滚动查看谈论?超级"的一半.
Here's a more thorough explanation, scroll about half way down where it talks about "? super".
这篇关于为什么不能将一个对象添加到列表中?超级号码> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!