Unchecked warnings and heap pollution with varargs + generics
"Heap pollution" is when a variable of a parameterized type ends up referring to an object that isn't
actually of that type -- something the type system is supposed to prevent, but generic varargs
(List<String>... lists) and raw types can both defeat. The compiler warns (unchecked) rather than errors,
because it genuinely can't verify safety at those points -- which means the resulting ClassCastException
can surface far from, and long after, the actual unsafe operation.
import java.util.*;
// javac warns here: "Possible heap pollution from parameterized vararg type List<String>"
static void dangerousVarargs(List<String>... lists) {
Object[] arr = lists; // legal -- List<String>[] IS an Object[] at runtime, thanks to erasure
arr[0] = Arrays.asList(42); // compiles! arr's static type is just Object[] here
String s = lists[0].get(0); // ClassCastException -- the "String" was actually an Integer
}
try {
dangerousVarargs(Arrays.asList("a", "b"));
} catch (ClassCastException e) {
System.out.println("ClassCastException from heap pollution: " + e.getMessage());
}
A raw type erases generic checking for that variable entirely -- the resulting failure surfaces far from where the actual bad value was inserted, which is exactly what makes this class of bug painful to debug:
@SuppressWarnings("unchecked")
static List rawReturningList() {
List raw = new ArrayList(); // raw type: zero generic type-checking on this variable
raw.add(123); // compiles fine -- raw type accepts any Object
raw.add("also fine");
return raw;
}
List<String> unchecked = rawReturningList(); // "unchecked conversion" warning, compiler just trusts you
System.out.println("contents look fine so far: " + unchecked);
try {
for (String s : unchecked) {
System.out.println(" element: " + s);
}
} catch (ClassCastException e) {
System.out.println("ClassCastException far from where 123 was actually added: " + e.getMessage());
}