- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下类(class)
public class Animal
public class Dog extends Animal
public class Cat extends Animal
为了测试,我有一个驱动程序类。
public class Driver {
public static void main(String[] args){
List<? extends Animal> animalList = Arrays.<Dog>asList(new Dog(), new Dog(), new Dog());
animalList.add(new Dog()) // Compilation error
}
}
默认情况下,列表是不变类型的容器。例如说我们有 List<Object> objectList
, ArrayList<String> stringList
我们不能将 stringList 替换为 objList。这将导致编译错误
我的尝试是使列表像在 Driver 类中一样具有协变性。
根据<? extends Animal>
我们可以应用任何属于 Animal 子类型的对象,包括 Animal 类型。
但是我在指示的行中遇到了编译问题。有人可以从理论上解释我哪里出错了。
最佳答案
我认为您误解了通用通配符 (?
)。来自Java tutorial on the subject :
There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into shapes in the body of the method. For instance, this is not allowed:
public void addRectangle(List<? extends Shape> shapes) {
// Compile-time error!
shapes.add(0, new Rectangle());
}You should be able to figure out why the code above is disallowed. The type of the second parameter to
shapes.add()
is? extends Shape
-- an unknown subtype ofShape
. Since we don't know what type it is, we don't know if it is a supertype ofRectangle
; it might or might not be such a supertype, so it isn't safe to pass aRectangle
there.
Java 泛型集合不是协变的;参见例如Java theory and practice: Generics gotchas寻求解释。
关于java - 如何使java列表协变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11484400/
在我的设置中,我试图有一个界面 Table继承自 Map (因为它主要用作 map 的包装器)。两个类继承自 Table - 本地和全局。全局的将有一个可变的映射,而本地的将有一个只有本地条目的映射。
Rust Nomicon 有 an entire section on variance除了关于 Box 的这一小节,我或多或少地理解了这一点和 Vec在 T 上(共同)变体. Box and Vec
我是一名优秀的程序员,十分优秀!