我将展示两种泛型声明的样式。在第一部分中,我使用了List上的泛型上界声明,如下所示:
List<? extends Animal> totList = new ArrayList<Animal>();
但是如果你尝试将一个Animal对象添加到列表中,就会出现以下错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method add(capture#1-of ? extends Animal) in the type List<capture#1-of ? extends Animal> is not applicable for the arguments (Animal)
at GenericsType.main(GenericsType.java:39)
但是就像在Part2中一样,如果我按照以下格式在泛型类内声明列表,在向列表中添加(Animal对象)或(Animal子类对象)时不会抛出任何错误。
class GenericAnimal<T extends Animal>
{
List<T> genList = new ArrayList<T>();
}
在part2中为什么没有抛出错误,两种声明风格有什么区别。
示例代码:
1.Animal.java
public class Animal {
private String name;
private int height;
public void animalJump()
{
if(height>100)
{
System.out.println(name+" with height-"+height+" can JUMP");
}
else
System.out.println(name+" with height-"+height+" cannot jump");
}
public void setName(String name) {
this.name = name;
}
public void setHeight(int height) {
this.height = height;
}
public Animal(String name, int height) {
setName(name);
setHeight(height);
}
}
2.GenericsType.java
import java.util.*;
import Animal;
import Animal.Cannine;
import Animal.Feline;
import Animal.Feline.Cat;
import Animal.Cannine.Dog;
public class GenericsType {
public static List<? extends Animal> totList = new ArrayList<Animal>();
public static void processAllfunc1()
{
for(Animal a : totList)
{
a.animalJump();
}
}
public static void main(String args[])
{
// Part 1
totList.add(new Animal("Animal1",21)); // Error: Unresolved compilation problem:
processAllfunc1();
// Part 2
GenericAnimal<Animal> genericanimal = new GenericAnimal<Animal>();
genericanimal.genList.add(new Animal("Animal2",22)); // No Error, why?
genericanimal.genList.add(new Cat("Cat4",204)); // No Error for Cat also, why?
genericanimal.processAllfunc2();
}
}
3.GenericAnimal.java
public class GenericAnimal<T extends Animal> {
public List<T> genList = new ArrayList<T>();
public void processAllfunc2() {
for (T a : genList) {
a.animalJump();
}
}
}