如何在Java泛型中使用逆变?
2022-09-01 12:30:29
在 Java 中,协方差允许 API 设计人员指定实例可以泛化为特定类型或该类型的任何子类型。例如:
List<? extends Shape> shapes = new ArrayList<Circle>();
// where type Circle extends Shape
逆变则相反。它允许我们指定实例可以泛化为某种类型或超类型。
List<? super Shape> shapes = new ArrayList<Geometry>();
// where Shape extends Geometry
Java泛型的逆变有什么用处?你什么时候会选择使用它?