I have always had this one issue with arrays of ArrayLists. Maybe you can help.
//declare in class
private ArrayList[] x;
//in constructor
x=new
It shouldn't have been an error. A warning is enough. If nobody can create an ArrayList
, 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[] newArray(Class> classE, int length)
{
return (E[])java.lang.reflect.Array.newInstance(classE, length);
}
void test()
ArrayList[] 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.