问题描述
我读过 O'Reilly 的书,因为我知道了这个get-put 原则.
I have read O'Reilly book, in that I came to know this get-put principle.
- 当您只从结构中获取值时,使用
通配符.
- 当您只将值放入结构中时,请使用
通配符.
- 当你们都想从/向结构中获取和放入时,不要使用通配符.
例外是:
除了值
null
通配符声明的类型中>,属于每个引用类型.
除了 Object
类型的值之外,您无法从使用 通配符声明的类型中获取任何内容,它是每个引用类型的超类型.
You cannot get anything out from a type declared with an wildcard except for a value of type
Object
, which is a
谁能帮我深入探索这条规则?如果可能,请把它们分层放置.
Can anyone help me to explore this rule at depth? If possible, please put them hierarchical manner.
推荐答案
考虑一堆香蕉.这是一个 Collection 因为它是特定种类水果的集合 - 但您不知道(从该声明中)它是哪种水果的集合.你可以从它得到一个物品并且知道它肯定是一个水果,但你不能添加到它——你可能试图在一堆苹果中添加一个香蕉,这肯定是错误的.您可以向它添加
null
,因为这对于任何种类的水果来说都是一个有效值.
Consider a bunch of bananas. This is a Collection<? 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.
现在考虑一个水果碗.这是一个 Collection
,因为它是某种大于"Banana
类型的集合(例如,Collection
或 Collection;
).你可以绝对在上面加一根香蕉,但是如果你从碗里拿出一个东西,你不知道会得到什么——它很可能不是香蕉.您所知道的只是它是一个有效的(可能是 null
)Object
引用.
Now consider a fruitbowl. This is a Collection<? , 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.
(一般来说,对于 Java 泛型问题,Java 泛型常见问题解答是一个很好的资源,其中包含几乎所有与泛型相关的问题的答案.)
(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.)
这篇关于get-put原则的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!