【问题标题】:Recursive Function Not Adding Items to ArrayList in Java递归函数不向Java中的ArrayList添加项目
【发布时间】:2020-03-19 13:45:16
【问题描述】:

我正在尝试将数组数组添加到 Java 中的 ArrayList。只有递归的最后一次迭代被多次添加到 ArrayList 中。我有以下 Java 类:

import java.util.ArrayList;

public class Test {
    ArrayList<int[][]> result;
    int[][] part;

    public Test() {
        result = new ArrayList<int[][]>();
        part = new int[2][2];
    }

    public void fill(int i) {
        if(i > 0) {
            part[0][0] = i;
            result.add(part);
            i--;
            fill(i);
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.fill(4);

        for(int l = 0; l < test.result.size() - 1; l++) {
            for(int i = 0; i < 2; i++) {
                for(int j = 0; j < 2; j++) {
                    System.out.print(test.result.get(l)[i][j] + " ");
                }
                System.out.println();
            }
            System.out.println("-----");
        }
    }
}

当我运行它时,我得到以下结果:

1 0 
0 0 
-----
1 0 
0 0 
-----
1 0 
0 0 
-----

我期望的地方:

3 0 
0 0 
-----
2 0 
0 0 
-----
1 0 
0 0 
-----

【问题讨论】:

    标签: java arrays recursion arraylist multidimensional-array


    【解决方案1】:

    这是因为您不断添加相同的对象part 三次。最后一次更新“坚持”,而之前的更新被覆盖。

    将数组初始化移动到递归方法的主体中可以解决这个问题:

    public void fill(int i) {
        if(i > 0) {
            int[][] part = new int[2][2];
            part[0][0] = i;
            result.add(part);
            i--;
            fill(i);
        }
    }
    

    同时从Test 类中删除part 的声明,因为它不再使用。

    【讨论】:

    • 如果part数组需要被类中的其他方法访问,你会如何解决这个问题?
    • @Dynamic 没有一个“部分”,您的示例中有三个;可能更多。 result 都有,你可以随意访问任意数组。
    【解决方案2】:

    fill 方法获取数组,将其在 [0][0] 的值设置为 i 并将其添加到列表中。

    然后,它采用相同的数组(实际上是对该数组的引用),将其在[0][0] 的值覆盖为i 并将其添加到列表中。

    所以,您多次添加了同一个数组,但您覆盖了其中的第一个值。

    ​

    [注意]

    Test 类的属性是包私有的。如果没有理由做任何其他事情,我建议您将可见性设置为 private。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 2015-02-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多