将元素添加到List <?扩展超类>,澄清需要 [英] Adding elements to List<? extends Superclass>, clarification needed
问题描述
如果 A扩展X,
则以下声明有效
名单< ;?扩展X> list = new ArrayList< A>();
它似乎是一个列表可以包含扩展X的元素的集合。因此, code> new A()应该符合条件。
是的,事实并非如此。为什么会这样?
你几乎已经知道了。 列表与LT ;?扩展X>
意味着某种类型的列表(我实际上不知道),它是X的一个子类型(或者可能是X本身)。
问题是如果X是 有关更多信息,请阅读项目28:使用有界通配符提高API灵活性 Number
。然后列表<?扩展X>
意味着列表< Double>
或 List< Integer>
,你刚刚说过的你实际上不知道。您不能在 List< Integer>
中插入任何 Number
。因此,由于您不知道列表元素的类型,因此您无法将任何 插入到 List<中扩展Number>
。但是,您可以从列表中检索值,并保证列表中包含的任何值至少 a Number
$ p
$ b 扩展
和超级
关键字在Java泛型中意味着什么时候使用。
If A extends X,
the following declaration is valid
List<? extends X> list = new ArrayList<A>();
It seems to be that a list would hold a collection of elements that extend X. As such, new A()
should qualify.
Yes, it does not. Why is that?
You've almost got it. List<? extends X>
means "a list of some type (which I don't actually know) which is a subtype of X (or possibly X itself)".
The problem is if X is, for example, Number
. Then List<? extends X>
means List<Double>
or List<Integer>
or some other type, which you've just said you don't actually know. You can't insert any Number
into a List<Integer>
. So, since you don't know the type of the elements of the list, you can't insert anything into a List<? extends Number>
. You can, however, retrieve values from the list, and you are guaranteed that any value contained in the list is at least a Number
.
For more information, read Item 28: Use bounded wildcards to increase API flexibility in Effective Java, 2nd Ed. by Joshua Bloch (a book which every Java programmer should have on their bookshelf). In particular, this item explains the mnemonic PECS, meaning "producer extends, consumer super", which will help you remember what the extends
and super
keywords mean in Java generics and when they should be used.
这篇关于将元素添加到List <?扩展超类>,澄清需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!