简体   繁体   English

递归中的ArrayLists的ArrayList

[英]ArrayList of ArrayLists in Recursion

I've been working on a larger project, and ran into a problem which I have replicated here in a much simpler fashion. 我一直在研究一个更大的项目,并遇到了一个我在这里以更简单的方式复制的问题。 What I'm trying to do is to add an ArrayList of Integers into another ArrayList. 我要做的是将一个Integers的ArrayList添加到另一个ArrayList中。 The problem is that every ArrayList I add into the larger ArrayList gets updated as if they were all the same. 问题是我添加到较大的ArrayList中的每个ArrayList都会更新,就好像它们都是一样的。

public class RecursionTest {
static ArrayList<Integer> test = new ArrayList<Integer>();
static ArrayList<ArrayList<Integer>> test1 = new ArrayList<ArrayList<Integer>>();

public static void testRecurse(int n) {
    test.add(n);
    if (n % 2 == 0) {
        test1.add(test);
    }
    if (n == 0) {   
        for (ArrayList<Integer> a : test1) {
            for (Integer i : a) {
                System.out.print(i + "  ");
            }
            System.out.println();
        }
        return;
    }       
    testRecurse(n - 1);     
}

public static void main(String[] args) {        
    testRecurse(10);
}
}

The output I get is: 我得到的输出是:

10  9  8  7  6  5  4  3  2  1  0  
10  9  8  7  6  5  4  3  2  1  0  
10  9  8  7  6  5  4  3  2  1  0  
10  9  8  7  6  5  4  3  2  1  0  
10  9  8  7  6  5  4  3  2  1  0  
10  9  8  7  6  5  4  3  2  1  0  

When it should be: 它应该是:

10  
10  9  8  
10  9  8  7  6  
10  9  8  7  6  5  4  
10  9  8  7  6  5  4  3  2  
10  9  8  7  6  5  4  3  2  1  0   

Can someone explain to me what is happening here? 有人可以向我解释这里发生了什么吗? And perhaps suggest a work around for such a situation. 也许建议解决这种情况。

You are adding the exact same object test to the ArrayList over and over again. 您正在反复向ArrayList添加完全相同的对象test This is why they are all getting modified together. 这就是他们一起被修改的原因。

Everytime you want to add it, you need to create a new ArrayList<Integer>() before you add it. 每次要添加它时,都需要在添加之前创建一个new ArrayList<Integer>()

You can try replacing 你可以尝试更换

test1.add(test);

with

test = new ArrayList<Integer>(test);
test1.add(test);

This makes a copy of the current test and then adds it to the list. 这将生成当前测试的副本,然后将其添加到列表中。

This would still mean that the Integer elements contained in the ArrayList would exhibit the same bug, since this is a shallow copy, but since you are not modifying them, it is ok for this case. 这仍然意味着ArrayList包含的Integer元素会出现相同的bug,因为这是一个浅拷贝,但由于你没有修改它们,所以对于这种情况是可以的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM