如何解决为什么我不能相互分配集合?
我有继承层次形状->矩形->方形
我有带参数 T 的 ShapeCollection 类来放置任何形状类类型:形状、矩形、方形。 但我不明白,为什么这是工作:
List<Rectangle> rectangleList = new ArrayList<>();
List<? extends Shape> shapeList = rectangleList;
但这是行不通的
List<ShapeCollection<Rectangle>> recCallList = new ArrayList<>();
List<ShapeCollection<? extends Shape>> shapeCallList = recCallList;
解决方法
Java 泛型是不变的,这意味着 List<S>
和 List<T>
是不相关的类型,即使 S
是 T
的子类型。
就您而言,这意味着 List<ShapeCollection<Rectangle>>
与 List<ShapeCollection<? extends Shape>>
无关,即使 ShapeCollection<Rectangle>
是 ShapeCollection<? extends Shape>>
的子类型。
如果您想要方差,则必须使用有界通配符来声明。也就是说,List<Rectangle>
和 List<Circle>
的共同超类型是 List<? extends Shape>
。同样,List<ShapeCollection<Rectangle>>
和 List<ShapeCollection<Circle>>
的共同超类型是 List<? extends ShapeCollection<? extends Shape>>
。
我假设 ShapeCollection
是用类似 class ShapeCollection<T extends Shape> {}
的东西声明的。
这与 subtyping and wildcards 在 Java 中的工作方式有关。想象一下,Java 允许你做你想做的事:
List<ShapeCollection<Rectangle>> recCallList = new ArrayList<>();
List<ShapeCollection<? extends Shape>> shapeCallList = recCallList; // imagine it's ok
ShapeCollection<Square> squareCollection = ...;
shapeCallList.add(squareCollection); // uh-oh,mix of Square and Rectangle
现在您可以将 ShapeCollection<Square>
添加到 recCallList
,这很糟糕。您可以对 ShapeCollection<Square>
执行 List<ShapeCollection<? extends Shape>>
的原因是 ShapeCollection<Square>
是 ShapeCollection<? extends Shape>
的子类,如这张取自 Oracle 文档的图片所示:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。