This question is specific to using varargs with generic-fied Enum<E>
s:
Why do I get this warning Type safety: Potential heap pollution via varargs parameter elements
if I define the method the like this:
<E extends Enum<E>> void someMethod(E... elements)
As opposed to this:
<E extends Enum<E>> void someMethod(E[] elements)
Accordingly, what should I look out for before declaring the method @SafeVarargs
?
Similar questions
This question is similar to these questions regarding Collection<T>...
but the scenarios shown in those answers do not seem to apply with Enum<E>...
:
- Potential heap pollution via varargs parameter
- Type safety: Potential heap pollution via varargs parameter subtrees
- Potential heap pollution via varargs parameter
- Eclipse different behaviour for "Unchecked" warning due to "Potential heap pollution via varargs parameter". How to fix?
It is the reverse of this question which questions why there are no warning:
Sample code
This is what I tried to pollute the heap, but each bad attempt results in java.lang.ArrayStoreException
and not a polluted array.
I am using Eclipse 4.6.0 and Java JDK 8u74.
public static void main(String[] args) {
Foo[] x = { Foo.A };
someMethod(x);
Foo y = x[0]; // How does one get a ClassCastException here?
}
private static enum Foo {
A, B, C,
}
private static enum Bar {
X, Y, Z,
}
// This produces a "Type safety" warning on 'elements'
private static <E extends Enum<E>> void someMethod(E... elements) {
Object[] objects = elements;
// Test case 1: This line throws java.lang.ArrayStoreException
objects[0] = "";
// Test case 2: Program terminates without errors
objects[0] = Foo.A;
// Test case 3: This line throws java.lang.ArrayStoreException
objects[0] = Bar.X;
}