I have a constructor like below
public MyConstructor(MyObject<T> ... objects) {
// ...
}
Eclipse warns me with the following message:
Type safety: Potential heap pollution via varargs parameter objects
I change the constructor like this:
public MyConstructor(MyObject<T>[] objects) {
// ...
}
Now, the warning disappears. However, I think the potential danger is not solved.
Is this workaround valid ?
In a way it is a workaround. Creating arrays of non-reifiable component type is unsafe. Therefore such array creation expressions are disallowed by the compiler:
// List<String> is erased to List => disallowed
Object example = new List<String>[] { null, null };
// List<?> is effectively reifiable => allowed
Object example = new List<?>[] { null, null };
Yet, hidden array creations via variable arity methods, such as Arrays.asList
, are allowed.
// RHS amounts to Arrays.asList(new List<String>[] { null, null })
List<List<String>> example = Arrays.asList(null, null);
Since you disallowed this array creation, your heap can no longer be polluted. But: How are you ever going to call that constructor?
Please note that your constructor may not pollute the heap at all. The only way it does is if
MyObject<?>[]
or Object[]
) orIf you do neither you can mark the constructor as having @SafeVarargs
and the warning goes away.