Java get-put 原理的解释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1292109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Explanation of the get-put principle
提问by JavaResp
I have read O'Reilly book, in that I came to know this get-put principle.
我读过 O'Reilly 的书,因为我知道了这个get-put 原则。
- Use an
extends
wildcard when you only getvalues out of a structure.- Use a
super
wildcard when you only putvalues into a structure.- And don't use a wildcard when you both want to get and put from/to a structure.
extends
当您只从结构中获取值时使用通配符。super
当您只将值放入结构中时,请使用通配符。- 当你们都想从/向结构中获取和放入时,不要使用通配符。
Exceptionsare:
例外情况是:
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.
extends
除了null
属于每个引用类型的 value 之外,您不能将任何内容放入使用通配符声明的类型中。
super
除了 type 的值(Object
它是每个引用类型的超类型)之外,您无法从使用通配符声明的类型中获取任何内容。
Can anyone help me to explore this rule at depth? If possible, please put them hierarchical manner.
谁能帮我深入探索这条规则?如果可能,请把它们分层放置。
采纳答案by Jon Skeet
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 getan item from it and know it will definitely be a fruit, but you can't addto it - you might be trying to add an apple to a bunch of bananas, which would definitely be wrong. You canadd null
to it, as that will be a valid value for anykind of fruit.
考虑一堆香蕉。这是Collection<? extends Fruit>
因为它是一种特定种类的水果的集合 - 但你不知道(从那个声明中)它是一种什么样的水果。你可以从中得到一个物品并且知道它肯定是一个水果,但你不能添加它——你可能试图在一堆香蕉中添加一个苹果,这肯定是错误的。您可以添加null
它,因为这对于任何种类的水果都是有效的值。
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 definitelyadd a banana to this, but if you fetch an item from the bowl you don't know what you'll get - it may well notbe a banana. All you know for sure is that it will be a valid (possibly null
) Object
reference.
现在考虑一个水果碗。这是Collection<? super Banana>
,因为它是某种“大于”类型的集合Banana
(例如,Collection<Fruit>
or Collection<TropicalFruit>
)。您绝对可以在其中添加香蕉,但是如果您从碗中取出物品,您不知道会得到什么 - 它很可能不是香蕉。您所知道的只是,它将是一个有效的(可能null
)Object
参考。
(In general, for Java generics questions, the Java Generics FAQis an excellent resource which contains the answer to almost anything generics-related you're likely to throw at it.)
(一般来说,对于 Java 泛型问题,Java 泛型常见问题是一个很好的资源,其中包含几乎所有您可能会抛出的与泛型相关的答案。)