参考
The Java™ Tutorials -
wikipedia - Heap pollution
概念
下面这段话来自维基百科
In the Java programming language, heap pollution is a situation that arises when a variable of a parameterized type refers to an object that is not of that parameterized type. This situation is normally detected during compilation and indicated with an unchecked warning. Later, during runtime heap pollution will often cause a ClassCastException.
大意就是, Heap Pollution指的是当一个泛型类引用实际指向了一个不是该引用继承结构内的对象实例. 即引用类型并不是实际对象的同类, 或者其父类. 这种情况通常会在运行时造成ClassCastException
异常.
例子
public static void rawType(){
Set set = new HashSet<String>();
// 因为Raw Type不会像Set<?>一样被编译器进行安全检查
// 所以会允许添加任何对象
set.add(20); // warning
Iterator<String> iterator = set.iterator(); // warning
while (iterator.hasNext()){
// Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
String string = iterator.next();
// 如果像下面这样调用, 不涉及(String)类型转换
// 不会报错
// iterator.next();
}
}
public static void objectCast(){
List<String> stringList;
List<Integer> integerList = new ArrayList<>();
Object obj = integerList;
stringList = (List<String>) obj; // warning
stringList.add("Hello"); // no warning
// Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Integer integer = integerList.get(0);
}
@SafeVarargs 注解
只是去除编译器的警告而已.