In a way, this is a workaround. Creating arrays of an unsupported component type is unsafe. Therefore, such expressions for creating an array are prohibited 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 };
However, hidden arrays are allowed using arity variable methods such as Arrays.asList .
// RHS amounts to Arrays.asList(new List<String>[] { null, null }) List<List<String>> example = Arrays.asList(null, null);
Since you have forbidden the creation of this array, your heap can no longer be polluted. But: What are you going to call this constructor?
Note that your constructor may not pollute the heap at all. The only way to do this is if
- it converts the array to a less specific type (i.e.
MyObject<?>[] or Object[] ) or - it allows the array to somehow escape (i.e. assign it to a field and return from the recipient or pass it to a potentially dangerous method).
If you do not, you can mark the constructor as having @SafeVarargs and the warning will disappear.
Ben schulz
source share