Java 为什么可以’;我们不是从逆变式中读出的吗

Java 为什么可以’;我们不是从逆变式中读出的吗,java,generics,contravariance,Java,Generics,Contravariance,我在学习Java中的泛型,我在学习协变和逆变。我理解协方差,为什么我们不能写协方差类型。但对我来说,矛盾是令人困惑的。我想知道为什么从反变项读取总是对象类型 假设我们有以下几节课 Class Animal Class Dog extends Animal Class Tiger extends Animal 现在,考虑下面的代码 List<Animal> animals = new ArrayList<>(); List<? super Animal> co

我在学习Java中的泛型,我在学习协变和逆变。我理解协方差,为什么我们不能写协方差类型。但对我来说,矛盾是令人困惑的。我想知道为什么从反变项读取总是对象类型

假设我们有以下几节课

Class Animal
Class Dog extends Animal
Class Tiger extends Animal

现在,考虑下面的代码

List<Animal> animals = new ArrayList<>();
List<? super Animal> contraVarianceList=animals;

animals.add(new Dog()); // Allowed
animals.add(new Tiger()); //Allowed
Animal animal = contraVarianceList.get(0); // Not allowed. Why?
List animals=new ArrayList();

List我想你是想问为什么是
Animal=contraVarianceList.get(0)不允许

这样想:

List<Animal> animals=  new ArrayList<>();
List<Object> objects = new ArrayList<>();

List<? super Animal> contraVarianceList = animals;
List<? super Animal> contraVarianceList2 = objects;

animals.add(new Dog()); // Allowed
animals.add(new Tiger()); //Allowed

objects.add(new Dog()); // Allowed
objects.add(new Tiger()); //Allowed

//there is no type difference between contraVarianceList and contraVarianceList2
Animal animal = contraVarianceList.get(0);  //compiler will complain
Animal animal2 = contraVarianceList2.get(0); //compiler will complain

保证您可以将该方法同时用于
List
List

现在我明白了。非常感谢你简洁明了的解释
void populateAnimals(List<? super Animal> animals) {
  //whatever code
  animals.add(...);
}