gpt4 book ai didi

java - 将二维 ArrayList 添加到三维 ArrayList 作为值传递

转载 作者:行者123 更新时间:2023-12-01 19:57:51 25 4
gpt4 key购买 nike

我正在尝试将二维数组列表作为按值传递添加到三维数组列表中...因此,当清除二维数组列表时,三维数组列表内的列表也不会被清除...

代码:

package Main;
import java.util.ArrayList;

public class QuickTest {
private static void printThreeDimList(ArrayList<ArrayList<ArrayList<Integer>>> threeDimList){
int threeDimListIndex = 0;
for (ArrayList<ArrayList<Integer>> twoDimList: threeDimList){
System.out.println("*************** threeDimList: Index(" + threeDimListIndex + ") ***************");
for (ArrayList<Integer> oneDimList: twoDimList){
System.out.println(oneDimList);
}
threeDimListIndex++;
}
}

public static void main(String[] args) {
ArrayList<Integer> oneDimList = new ArrayList<>();
ArrayList<ArrayList<Integer>> twoDimList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<Integer>>> threeDimList = new ArrayList<>();

Integer firstNum = 1;
Integer secondNum = 100;
for (int threeDimIndex = 0; threeDimIndex < 3; threeDimIndex++){ // loops 3x
for (int i = 0; i < 4; i++){ // loops 4x
oneDimList.add(firstNum);
for (int j = 0; j < 5; j++){ // loops 5x
oneDimList.add(secondNum);
secondNum += 100;
}
twoDimList.add(new ArrayList<>(oneDimList));
oneDimList.clear();
firstNum++;
}
threeDimList.add(twoDimList); // <- bug is here, it's adds pass-by-reference, and instead needs to be pass-by-value
twoDimList.clear(); // so not only is this "twoDimList" cleared, but the one inside "threeDimList" is cleared too... and we only want to clear this "twoDimList"
}

printThreeDimList(threeDimList);
}
}

实际输出:

*************** threeDimList: Index(0) ***************
*************** threeDimList: Index(1) ***************
*************** threeDimList: Index(2) ***************

预期输出:

*************** threeDimList: Index(0) ***************
[1, 100, 200, 300, 400, 500]
[2, 600, 700, 800, 900, 1000]
[4, 1100, 1200, 1300, 1400, 1500]
[5, 1600, 1700, 1800, 1900, 2000]
*************** threeDimList: Index(1) ***************
[6, 2100, 2200, 2300, 2400, 2500]
[7, 2600, 2700, 2800, 2900, 3000]
[8, 3100, 3200, 3300, 3400, 3500]
[9, 3600, 3700, 3800, 3900, 4000]
*************** threeDimList: Index(2) ***************
[10, 4100, 4200, 4300, 4400, 4500]
[11, 4600, 4700, 4800, 4900, 5000]
[12, 5100, 5200, 5300, 5400, 5500]
[13, 5600, 5700, 5800, 5900, 6000]

有人知道如何做到这一点吗?

最佳答案

改变

threeDimList.add(twoDimList);

threeDimList.add(new ArrayList<>(twoDimList));

这样 thirdDimList 将包含 3 个不同的 ArrayList 实例。

关于java - 将二维 ArrayList 添加到三维 ArrayList 作为值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48861738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com