Java question about ArrayList[] x

后端 未结 6 1551
臣服心动
臣服心动 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条回答
  •  后悔当初
    2021-02-06 09:20

    Run the flowing code:

    public class Test {
        ArrayList[] f0;
        ArrayList f1;
        ArrayList[] f2;
        public static void main(String[] args) {
            Test t = new Test();
            Field[] fs = t.getClass().getDeclaredFields();
            for(Field f: fs ){
                System.out.println(f.getType().getName());
            }
    
        }
    
    }
    

    You will get:

    [Ljava.util.ArrayList;
    java.util.ArrayList
    [Ljava.util.ArrayList;
    

    Because Java don't support generic array. When you declare:

    private ArrayList[] x;
    

    The compiler will think it is :

    private ArrayList[] x;
    

    So, you should do like that:

    int n = 10;
    ArrayList[] f = new ArrayList[n];
    for(int i=0;i();
    }
    

提交回复
热议问题