gpt4 book ai didi

java - Java泛型中如何使用逆变?

转载 作者:IT老高 更新时间:2023-10-28 21:21:01 26 4
gpt4 key购买 nike

在 Java 中,协方差允许 API 设计者指定实例可以泛化为某种类型或该类型的任何子类型。例如:

List<? extends Shape> shapes = new ArrayList<Circle>(); 
// where type Circle extends Shape

逆变换反了。它允许我们指定一个实例可以泛化为某种类型或父类(super class)型。

List<? super Shape> shapes = new ArrayList<Geometry>();
// where Shape extends Geometry

Java 泛型的逆变性有何用处?你会选择什么时候使用它?

最佳答案

这是来自 Java Generics and Collections 的相关摘录:

2.4。获取和放置原则

尽可能插入通配符可能是个好习惯,但您如何决定使用哪个通配符?你应该在哪里使用extends,你应该在哪里使用super,什么地方不适合使用通配符?

幸运的是,一个简单的原则决定了哪个是合适的。

The Get and Put Principle: 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 get and put.

我们已经在复制方法的签名中看到了这个原理:

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

该方法从源 src 中获取值,因此使用 extends 通配符声明它,并将值放入目标 dst,因此使用 super 通配符声明。每当您使用迭代器时,都会从结构中获取值,因此请使用 extends通配符。这是一个采用数字集合的方法,将每个数字转换为 double ,并总结:

public static double sum(Collection<? extends Number> nums) {
double s = 0.0;
for (Number num : nums) s += num.doubleValue();
return s;
}

关于java - Java泛型中如何使用逆变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3861132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com