I have been looking at various answers and articles regarding heap pollution when using non-reifiable varargs parameters. All examples I have found use an Object[]
conversion followed by an array element write. The heap pollution only ever seems to occur in this manner, for example:
public void example(List<Integer>... lists) {
// lists[0] = Collections.singletonList("A!");
Object[] objects = lists;
objects[0] = Collections.singletonList("B!"); // (pollutes!)
}
Some other articles (such as this SO answer) also appear to be incorrect or entirely misleading:
So now we have a
List<String>
that actually contains anInteger
, and it's floating around, safely.
The code presented in the answer never modifies the lists themselves, just the temporary varargs array within the faultyMethod
scope. This runnable demo shows that neither of the two lists are ever polluted and both retain their original String
objects (contrary to the answer suggesting they are polluted with an Integer
).
I now have two resulting questions:
Why does the compiler need to warn us on every possible method when the vast majority of them will not be converting to
Object[]
- surely it would be better to only warn on the problematicObject[]
line itself? Perhaps there is a scenario where "possible heap pollution from parameterized vararg type" can occur without any explicitObject[]
conversion?Is the answer to the previous SO question incorrect or am I misinterpreting the statement?