Java 创建ArrayList的ArrayList<;整数>;

Java 创建ArrayList的ArrayList<;整数>;,java,multidimensional-array,arraylist,Java,Multidimensional Array,Arraylist,我正在尝试使用下面的代码创建多维ArrayList。我的代码很好地填充了内部ArrayList(localSolutions),但是当我尝试将该ArrayList添加到外部ArrayList(solutions)时,出现了一些问题,它反而添加了空的ArrayList public class MathCapstone { public static void main(String[] args) { ArrayList<ArrayList<Integer>>

我正在尝试使用下面的代码创建多维ArrayList。我的代码很好地填充了内部ArrayList(localSolutions),但是当我尝试将该ArrayList添加到外部ArrayList(solutions)时,出现了一些问题,它反而添加了空的ArrayList

public class MathCapstone {

public static void main(String[] args) {
    ArrayList<ArrayList<Integer>> list = entireList(10);

    for(int q = 0;q<list.size();q++) {
        System.out.println(list.get(q));
    }

public static ArrayList<ArrayList<Integer>> entireList(int max) {
    ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> localSolutions = new ArrayList<Integer>();

    for(int i = 1; i <= max; i++) {
        for(int j = 1; j < i; j++) {
           //System.out.println(j + "mod" + i + "=" + (j*j)%i);
            if ((j*j)%i == 1) {
                localSolutions.add(j);
            }
        }
        //System.out.println(localSolutions.toString());
        solutions.add(localSolutions);
        localSolutions.clear();
    }
    return solutions;
}
公共类数学顶点{
公共静态void main(字符串[]args){
ArrayList=entireList(10);

对于(int q=0;q您正在清除localSolutions列表

在Java中,只按值复制对对象的引用,而不是实际对象本身。因此,当在解决方案列表中添加本地解决方案列表时,本地解决方案引用和解决方案列表的第一个条目都指向同一对象

因此,当您清除本地解决方案列表时,您有效地清除了解决方案列表中的第一个条目。

您正在执行以下操作:

localSolutions.clear();
将列表添加到另一个列表不会添加列表的副本,而是添加相同的列表对象。您的代码在outerloop中所做的是用元素填充相同的列表,清空它,然后将其添加到
解决方案
解决方案
包含对相同的空列表的引用

您要做的是:

ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>();
for(int i = 1; i <= max; i++) {
    ArrayList<Integer> localSolutions = new ArrayList<Integer>();
    for(int j = 1; j < i; j++) {
       //System.out.println(j + "mod" + i + "=" + (j*j)%i);
        if ((j*j)%i == 1) {
            localSolutions.add(j);
        }
    }
    //System.out.println(localSolutions.toString());
    solutions.add(localSolutions);
}
ArrayList solutions=new ArrayList();

对于(int i=1;使用< <代码> HashMap <代码> >与<代码> > ARARYLIST/CODE无关。如果要使用的索引是0到某个数之间的所有数字,则您将丢失一点性能。如果需要非整数键,或者索引的分布稀疏,则哈希图更好。也请考虑<代码>列表S。olutions=new ArrayList()
@aclear16我拒绝了你对我答案的编辑,因为我所做的是故意的,也是修复的一部分。如果没有测试代码更改之类的好理由,请不要更改其他用户答案的语义-如果你认为你发现了一个bug,如果你不确定,最好添加一条注释。