用一个原生的引用一个具体泛型类型容器对象,往往可以添加别的对象,当从其容器取出元素强转时,才抛出其异常,不好发现问题的所在,这是你可以用Collections的一系类工具(checkedCollection(),checkedList(),checkedMap()等),来检查容器,让你在插入类型不正确对象情况下通过其运行时抛出ClassCastException异常来知道问题所在。
代码例子:
public class Pet extends Individual {
public Pet(String name) { super(name); }
public Pet() { super(); }
}
public class Dog extends Pet {
public Dog(String name) { super(name); }
public Dog() { super(); }
}
public class Cat extends Pet {
public Cat(String name) { super(name); }
public Cat() { super(); }
}
public class CheckedList {
@SuppressWarnings("unchecked")
static void oldStyleMethod(List probablyDogs) {
probablyDogs.add(new Cat());
}
public static void main(String[] args) {
List<Dog> dogs1 = new ArrayList<Dog>();
//编译和运行都会通过
oldStyleMethod(dogs1);
List<Dog> dogs2 = Collections.checkedList(
new ArrayList<Dog>(), Dog.class);
try {
//会抛出异常
oldStyleMethod(dogs2);
} catch(Exception e) {
System.out.println(e);
}
//安全编译通过
List<Pet> pets = Collections.checkedList(
new ArrayList<Pet>(), Pet.class);
pets.add(new Dog());
pets.add(new Cat());
}
}