通用 Class 创建
Generic Class Creation
任何人都可以给我解释以下内容..
List<? extends Shape> typeList = new ArrayList<>();
List<Shape> shapeList = new ArrayList<>();
typeList.addAll(shapeList); //1
typeList = shapeList; //2
此处 'line 1' 将无法编译,因为 typeList 被定义为采用一些扩展 Shape 的 class。但是编译器不知道哪个class。因此编译失败。
同样的逻辑适用于'line 2'。如何将 shapeList 分配给 typeList?为什么这一行没有给出编译错误?
当您声明为列表类型 ? extends Shape
时,您可以从列表中读取 Shape
个对象。但不要写信给它。因此列表或数据结构变为只读。这就是 addAll
无法编译的原因。
而当您使用 ? super Shape
时,列表变为只写。因此,如果您将代码替换为 ? super Shape
,您的代码将编译。
请参阅这篇关于协方差和逆方差的文章:
https://dzone.com/articles/covariance-and-contravariance
For contravariance we use a different wildcard called ? super T, where
T is our base type. With contravariance we can do the opposite. We can
put things into a generic structure, but we cannot read anything out
of it.
任何人都可以给我解释以下内容..
List<? extends Shape> typeList = new ArrayList<>();
List<Shape> shapeList = new ArrayList<>();
typeList.addAll(shapeList); //1
typeList = shapeList; //2
此处 'line 1' 将无法编译,因为 typeList 被定义为采用一些扩展 Shape 的 class。但是编译器不知道哪个class。因此编译失败。
同样的逻辑适用于'line 2'。如何将 shapeList 分配给 typeList?为什么这一行没有给出编译错误?
当您声明为列表类型 ? extends Shape
时,您可以从列表中读取 Shape
个对象。但不要写信给它。因此列表或数据结构变为只读。这就是 addAll
无法编译的原因。
而当您使用 ? super Shape
时,列表变为只写。因此,如果您将代码替换为 ? super Shape
,您的代码将编译。
请参阅这篇关于协方差和逆方差的文章:
https://dzone.com/articles/covariance-and-contravariance
For contravariance we use a different wildcard called ? super T, where T is our base type. With contravariance we can do the opposite. We can put things into a generic structure, but we cannot read anything out of it.