谁能给我解释一下以下内容..
List<? extends Shape> typeList = new ArrayList<>();
List<Shape> shapeList = new ArrayList<>();
typeList.addAll(shapeList); //1
typeList = shapeList; //2
此处“第 1 行”将无法编译,因为 typeList 被定义为采用一些扩展 Shape 的类。然而编译器不知道哪个类。因此编译失败。
相同的逻辑适用于“第 2 行”。如何将 shapeList 分配给 typeList?为什么这一行没有给出编译错误?
最佳答案
当你声明为列表类型时?扩展 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.
关于java - 通用类创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50158836/