Java question about ArrayList[] x

后端 未结 6 1714
臣服心动
臣服心动 2021-02-06 08:41

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          


        
6条回答
  •  Happy的楠姐
    2021-02-06 09:09

    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.

提交回复
热议问题