java - 关于 Java 泛型下限用法 : ? super T

标签 java generics

我正在尝试深入了解下限通配符的用法。我正在尝试编写一个通用方法 copy它复制了一个 List 的内容给另一个。我想出了这个方法签名:

<T> void copy(List<T> dest, List<? extends T> src)

我认为这个签名很全面,可以解决所有场景。但是,我看到在 Java Collections 类中,方法签名是这样的:

<T> void copy(List<? super T> dest, List<? extends T> src)

我不明白他们为什么使用 List<? super T> dest而不仅仅是 List<T> dest .他们的签名是否有一些额外的灵 active ?

最佳答案

没有显式类型见证就没有实际区别。

如果没有像 Eran 所做的那样指定类型见证,这两种方法在灵 active 上没有差异。

本质上,的使用? super T over T 只是风格上的差异,但它是更好的实践,正如通过应用一些好的代码原则可以看出的那样:

  • 明确的意图:? super T 更明确地显示了 dest 应该采用的类型。
  • Modularity : 你根本不需要查看 src 上的类型约束,就可以知道 dest 可以采用什么类型。
  • Producer Extends, Consumer Super (PECS) : 生产者参数(下面的“in”)应该使用 extends 而消费者参数(下面的“out”)应该使用 super 关键字。

使用Java tutorials 也推荐 super T (他们甚至使用 copy 函数):

For purposes of this discussion, it is helpful to think of variables as providing one of two functions:

An "In" Variable
An "in" variable serves up data to the code. Imagine a copy method with two arguments: copy(src, dest). The src argument provides the data to be copied, so it is the "in" parameter.

An "Out" Variable
An "out" variable holds data for use elsewhere. In the copy example, copy(src, dest), the dest argument accepts data, so it is the "out" parameter.

You can use the "in" and "out" principle when deciding whether to use a wildcard and what type of wildcard is appropriate. The following list provides the guidelines to follow:

Wildcard Guidelines:

  • An "in" variable is defined with an upper bounded wildcard, using the extends keyword.
  • An "out" variable is defined with a lower bounded wildcard, using the super keyword.

关于java - 关于 Java 泛型下限用法 : ? super T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46997440/

相关文章:

java - 为什么 id 字段不能在 EclipseLink 的 where 子句中使用

java - 字段中的数据错误

java - 有什么方法可以为列表中的对象字段编写通用排序代码吗?

java - 未经检查的从通用 T 转换为可比较的阻止编译

c# - 如何在开放泛型类型中定义构造函数?

java - 创建包含分隔符的 on split 方法

java - 为什么Java类文件版本从45开始?

java - Unmarshal 在具有 List<T> 字段的泛型上生成空字段

c# - 如何指定 .NET 泛型约束中不允许的类型?

Java 泛型和静态工厂方法——语法