我读过 O'Reilly 的书,因为我了解了这个 get-put 原则。
- 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.
异常(exception)情况是:
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.
谁能帮我深入探索这条规则?如果可能,请把它们分层排列。
最佳答案
考虑一束香蕉。这是 Collection<? extends Fruit>
因为它是一种特定水果的集合——但你不知道(从那个声明中)它是什么水果的集合。您可以从中得到一个项目并且知道它肯定是一个水果,但你不能添加到它——你可能试图在一堆苹果中添加一个苹果香蕉,这肯定是错误的。您可以添加null
给它,因为这对于任何种水果都是有效的。
现在考虑一个水果碗。这是 Collection<? super Banana>
,因为它是某种“大于”Banana
的类型的集合(例如,Collection<Fruit>
或 Collection<TropicalFruit>
)。您可以绝对在其中添加一根香蕉,但是如果您从碗中取出一个元素,您不知道会得到什么 - 它很可能不是是一根香蕉.您可以肯定的是,它将是有效的(可能是 null
)Object
引用。
(一般来说,对于 Java 泛型问题,Java Generics FAQ 是一个很好的资源,它包含了几乎所有与泛型相关的问题的答案。)
关于java - get-put原理的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1292109/