在Java中初始化2d列表

Sau*_*abh 1 java list arraylist

我是Java的新手,并尝试创建一个大小不固定的二维列表.我有一个类如下所示:

public class q1 {
    List<List<Integer> > L = new ArrayList<List<Integer> >(); 

    public void set(int m,int n){
        //This is the function which would get the size of the 2d list
    }
}
Run Code Online (Sandbox Code Playgroud)

我看到了答案,但它们必须是固定大小的,例如:

ArrayList<String>[][] list = new ArrayList[10][10];
Run Code Online (Sandbox Code Playgroud)

但是,我希望不同对象的列表L的大小不同.还有其他选项,比如copyOf,但上述功能是否可以通过这个数组实现?

Sta*_*gle 6

你在问题中混合了两件事,ArrayLists并且arrays.ArrayList是一个可变大小的容器备份array.它有一个constructor你可以指定你需要的初始容量的地方,所以ArrayLists它看起来像:

public class q1 {
    List<List<Integer>> L; 
    public void set(int m, int n){
        L = new ArrayList<>(m); // assuming m is the number or rows
        for(int i = 0; i < m; ++i) {
            L.add(new ArrayList<>(n)); 
        }
        // now you have a List of m lists where each inner list has n items
    }
}
Run Code Online (Sandbox Code Playgroud)

对于数组,语法略有不同:

public class q1 {
    Integer[][] L; 
    public void set(int m, int n){
        L = new Integer[m][]; // assuming m is the number or rows
        for(int i = 0; i < m; ++i) {
            L[i] = new Integer[n]; 
        }
        // now you have a array of m arrays where each inner array has n items
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果所有内部数组都具有相同的长度,则(n)set方法可以简化为:

    public void set(int m, int n){
        L = new Integer[m][n]; // assuming m is the number or rows
        // now you have a array of m arrays where each inner array has n items
    }
Run Code Online (Sandbox Code Playgroud)