在Java中初始化二维列表

4

我是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
    }
}

我看到了答案,但它们必须具有固定的尺寸,例如:
ArrayList<String>[][] list = new ArrayList[10][10];

但是,我希望对于不同的对象,列表L能够有不同的大小。虽然还有其他选项,例如copyOf,但是仅凭这个数组就能实现上述功能吗?


3
请尽量避免混淆不同的术语。向量、动态数组和数组彼此完全不同。 - DodgyCodeException
哦,抱歉,我删掉了“vector”这个词,之前不知道“list”和“ArrayList”的区别。 - Saurabh
2个回答

10
你在问题中混淆了两个概念,ArrayListarraysArrayList是一个可变大小的容器,由一个array支持。 ArrayList有一个构造函数,您可以在其中指定所需的初始容量,因此使用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
    }
}

使用数组时,语法略有不同:

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
    }
}

此外,如果所有内部数组的长度都相同(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
    }

@Saurabh 当然没问题!很高兴能帮到你。 - StaticBeagle
L = new Integer[m][n]; 这行代码可以用更少的代码实现相同的功能。 - DodgyCodeException
@DodgyCodeException 是的,你说得完全正确。我一直在考虑列表,没有想到那种情况。我已经更新了我的答案,包括那种情况。很好的发现!感谢您的反馈。 - StaticBeagle
@Saurabh 我已更新我的答案,包括另一种初始化数组的方法。 - StaticBeagle
@StaticBeagle,感谢您提供更新的答案。我不知道为什么我的第一条评论关于感谢您的回答的话没有显示出来,我并没有删除它。 - Saurabh
@Saurabh 不用担心。 - StaticBeagle

1

对于List,没有特殊的语法,但您可以始终遍历较小列表的数量并逐个初始化它们。请注意,将大小传递给ArrayList的构造函数不会真正设置其大小,但它确实分配了空间,并且可能为您节省重新分配的时间:

public void set(int m,int n){
    l = new ArrayList<>(m);
    for (int i = 0; i < m; ++i) {
        l.add(new ArrayList<>(n));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接