将twoDimensional ArrayList添加到三维ArrayList作为传值

时间:2018-02-19 08:03:00

标签: java arraylist

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

守则:

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]

任何人都有任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:3)

更改

$data = array(
    array('name'=>'Coder 1', 'rep'=>'4096'),
    array('name'=>'Coder 2', 'rep'=>'2048'),
    //...
);

Coder::insert($data);

threeDimList.add(twoDimList);

这种方式threeDimList.add(new ArrayList<>(twoDimList)); 将包含3个不同的threeDimList个实例。