我試圖遵循在收集泛型Oracle文檔,對於上限和下限,但它是製造混亂。由於Java泛型界限混淆
import java.util.ArrayList;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
List<Dog> dogList = new ArrayList<>();
dogList.add(new Dog());
dogList.add(new Dog());
List<Cat> catList = new ArrayList<>();
catList.add(new Cat());
catList.add(new Cat());
List<Entity> entList = new ArrayList<>();
entList.add(new Entity());
entList.add(new Entity());
print(dogList);
print(catList);
print1(entList);
}
public static void print(List<? extends Animal> animals){
for(Animal an : animals){
System.out.println(an);
}
}
public static void print1(List<? super Animal> animals){
animals.add(new Animal());
animals.add(new Dog());
for(Object an : animals){
System.out.println(an);
}
}
}
class Entity {}
class Animal extends Entity{}
class Dog extends Animal {}
class Cat extends Animal {}
現在的困惑是,連變量的類型是List<? super Animal>
,我被允許添加狗的新實例,如animals.add(new Dog())
......爲什麼? 另外,如果我的變量類型爲List<? extends Animal>
,它不允許我添加動物或狗或實體的實例......任何原因?
>是通配符,是通用 –
Rugal