取得原则的解释 [英] Explanation of the get-put principle
问题描述
我读过O'Reilly的书籍,因为我开始知道这个 get-put原则 。 例外情况: 任何人都可以帮助我深入探索这条规则?如果可能的话,请把它们按层次分开。 解决方案
< blockquote>
扩展
通配符>值的结构。
super
通配符。
/ blockquote>
扩展
通配符除了值 null
,它属于每个引用类型。 超级
通配符,但<这是每种引用类型的超类型。
考虑一堆香蕉。这是一个集合<延伸Fruit>
,因为它是一种特定种类的水果的集合 - 但你不知道(来自该声明)它是一个集合的水果。你可以从它获取一个项目并知道它肯定会成为一个水果,但是你不能向它添加 - 你可能试图向一堆苹果添加一个苹果香蕉,这肯定是错的。您可以将 null
添加到它,因为这将是任何种水果的有效值。
现在考虑一个水果篮。这是一个集合<超级香蕉>
,因为它是某种类型的集合大于香蕉
(例如, Collection< Fruit> ;
或集合< TropicalFruit>
)。您可以 为此添加一根香蕉,但是如果您从碗中拿取一件物品,您不知道会得到什么 - 它可能不是香蕉。所有你知道的肯定是它将是一个有效的(可能 null
) Object
引用。
(一般来说,对于Java泛型问题, Java泛型常见问题解答是一个很好的资源,其中包含几乎所有与泛型有关的东西的答案,您可能会抛出它。)
I have read O'Reilly book, in that I came to know this get-put principle.
- Use an
extends
wildcard when you only get values out of a structure.- Use a
super
wildcard when you only put values into a structure.- And don't use a wildcard when you both want to get and put from/to a structure.
Exceptions are:
You cannot put anything into a type declared with an
extends
wildcard except for the valuenull
, which belongs to every reference type.You cannot get anything out from a type declared with an
super
wildcard except for a value of typeObject
, which is a super type of every reference type.
Can anyone help me to explore this rule at depth? If possible, please put them hierarchical manner.
Consider a bunch of bananas. This is a Collection<? extends Fruit>
in that it's a collection of a particular kind of fruit - but you don't know (from that declaration) what kind of fruit it's a collection of. You can get an item from it and know it will definitely be a fruit, but you can't add to it - you might be trying to add an apple to a bunch of bananas, which would definitely be wrong. You can add null
to it, as that will be a valid value for any kind of fruit.
Now consider a fruitbowl. This is a Collection<? super Banana>
, in that it's a collection of some type "greater than" Banana
(for instance, Collection<Fruit>
or Collection<TropicalFruit>
). You can definitely add a banana to this, but if you fetch an item from the bowl you don't know what you'll get - it may well not be a banana. All you know for sure is that it will be a valid (possibly null
) Object
reference.
(In general, for Java generics questions, the Java Generics FAQ is an excellent resource which contains the answer to almost anything generics-related you're likely to throw at it.)
这篇关于取得原则的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!