Consider these two methods:
// All good...
static <T> T extractFirst(T[] arr) {
if (arr.length > 0) return arr[0];
return null;
}
// Warning: "possible heap pollution from parameterized vararg type"
static <T> T extractFirstVarargs(T... arr) {
if (arr.length > 0) return arr[0];
return null;
}
The compiler gives a warning for the second method, but not for the first method which is just the de-sugared version of it. Why is that?
As far as I understand, I can produce unsafe code whenever I work with array types (since they are covariant due to historical reasons) or raw container types. How varargs factor into this is not clear to me.
EDIT: I know what heap pollution and type erasure is. But I fail to see why the warning is not also present in extractFirst
since I can cause heap pollution there as well.
EDIT 2: The warning doesn't even relate to generic params (T
), it also appears when using something like List<String>...
as a formal param.