java - get-put原理的解释

标签 java generics

我读过 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 value null, which belongs to every reference type.

  • You cannot get anything out from a type declared with an super wildcard except for a value of type Object, 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/

相关文章:

java - 在 jsch ChannelExec 上设置环境变量

Java - 使用泛型的多重签名?

java - 在 Java 1.5 版之前的 ArrayList 中,如何在没有泛型的情况下处理类型

c# - 在 C# 的通用列表中合并具有相同类型的项目的最有效方法是什么?

java - 如何将数组列表发送到另一个 Activity

java - 广播接收器不在后台工作

C# - 访问继承类中的属性

java - 这是创建接受任何类型集合的方法的最佳选择吗?

java - 2 行 ListView 未出现

java - 在 Java 中,写入文件比迭代数组慢多少?