[英]Recursive Function Not Adding Items to ArrayList in Java
我正在嘗試將數組數組添加到 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
-----
fill
方法獲取數組,將其[0][0]
的值設置為i
並將其添加到列表中。
然后,它采用相同的數組(實際上是對該數組的引用),將其在[0][0]
處的值覆蓋到i
並將其添加到列表中。
因此,您多次添加了相同的數組,但覆蓋了其中的第一個值。
[注意]
您的Test
類的屬性是包私有的。 如果沒有理由做任何其他事情,我建議您將可見性設置為private
。
這是因為您不斷添加相同的對象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
的聲明,因為它不再使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.