将元素添加到List <?扩展超类&GT,澄清需要 [英] Adding elements to List&lt;? extends Superclass&gt;, clarification needed

查看:129
本文介绍了将元素添加到List <?扩展超类&GT,澄清需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 A扩展X,则以下声明有效

 名单< ;?扩展X> list = new ArrayList< A>(); 

它似乎是一个列表可以包含扩展X的元素的集合。因此, code> new A()应该符合条件。



是的,事实并非如此。为什么会这样?

解决方案

你几乎已经知道了。 列表与LT ;?扩展X> 意味着某种类型的列表(我实际上不知道),它是X的一个子类型(或者可能是X本身)。



问题是如果X是 Number 。然后列表<?扩展X> 意味着列表< Double> List< Integer> ,你刚刚说过的你实际上不知道。您不能在 List< Integer> 中插入任何 Number 。因此,由于您不知道列表元素的类型,因此您无法将任何 插入到 List<中扩展Number> 。但是,您可以从列表中检索值,并保证列表中包含的任何值至少 a Number $ p
$ b

有关更多信息,请阅读项目28:使用有界通配符提高API灵活性 //books.google.com/books?id=Ft8t0S4VjmwCrel =nofollow> Effective Java,2nd Ed。 by Joshua Bloch(每个Java程序员应该在书架上都有的书)。特别是,这个项目解释了助记符PECS,意思是生产者延伸,超级消费者,这将帮助你记住扩展超级关键字在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 <?扩展超类&GT,澄清需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆