It shouldn't have been an error. A warning is enough. If nobody can create an ArrayList<Integer>[]
, there is really no point to allow the type.
Since javac doesn't do us the favor, we can create the array ourselves:
@SuppressWarnings("unchecked")
<E> E[] newArray(Class<?> classE, int length)
{
return (E[])java.lang.reflect.Array.newInstance(classE, length);
}
void test()
ArrayList<Integer>[] x;
x = newArray(ArrayList.class, 10);
The type constraint isn't perfect, caller should make sure the exact class is passed in. The good news is if a wrong class is passed in, a runtime error occurs immediately when assigning the result to x
, so it's fail fast.
>?
– Liviu T. Mar 11 '11 at 11:26