Video in progress
What is heap pollution, and when is it right to put @SafeVarargs on a method?
Heap pollution is a situation where a variable of a parameterized type actually points to an object of a different type. Generic varargs create a T[] array, which is why the compiler warns; you add @SafeVarargs if the method doesn't write into the array and doesn't hand it out.
📖 Answer
When a generic varargs method is called, the compiler creates an array like List<String>[], but because of erasure it's just a List[] at runtime. You can write any List into the array:
static void danger(List<String>... lists) {
Object[] arr = lists;
arr[0] = List.of(42); // no error at runtime
String s = lists[0].get(0); // ClassCastException here
}
The error shows up not where it was written but much later, on a completely different line. That's why a bug like this is hard to find.
Another hidden case is returning the array to the outside:
static <T> T[] toArray(T... items) { return items; }
static <T> T[] pair(T a, T b) { return toArray(a, b); } // actually an Object[]
String[] s = pair("a", "b"); // ClassCastException
Before you put @SafeVarargs, check that:
- the method doesn't write to the array elements;
- it doesn't return the array reference or give it to untrusted code;
- the method is
static,finalorprivate(you can only put the annotation on those and on constructors).
List.of(E...), Arrays.asList and Stream.of are safe examples in the JDK.
Sign up to mark studied questions and save your progress.