Java从数组复制数据而不是参考

时间:2016-02-26 03:15:31

标签: java arrays

在下面的代码中,我试图复制2d数组' cur,'在数组中交换两个值,并最终将它添加到一个arraylist我将在稍后的程序中使用。我的问题是,每次我在数组中切换这些值时都会出现这样的情况。 (具有克隆值' cur')它还会切换数组中的值' cur。'我很困惑,因为我尝试过clone(),Arrays.copyof,甚至为PuzzleNode类创建了一个新的构造函数,它从cur中获取值,但每次都是' cur。当循环的迭代结束时,它不会重置为其原始值。非常感谢任何帮助。

以下是代码:

//generate the puzzles and swap the tiles
    for (int i = 0; i < possibleSwaps.size(); i++) {
        //stores the 2d array of Nodes
        PuzzleNode temp = new PuzzleNode();
        //instantiate the 2d array and populate it with values of cur
        temp.puzzle = new Node[cur.puzzle.length][cur.puzzle[0].length];
        for (int j = 0; j < cur.puzzle.length; j++) {
            temp.puzzle[j] = cur.puzzle[j].clone();
        }

        for (int j = 0; j < cur.puzzle.length; j++) {
            for (int k = 0; k < cur.puzzle[0].length; k++) {
                if (temp.puzzle[j][k].value == possibleSwaps.get(i).value) {
                    //switch the values, values should always be distinct
                    int prev = temp.puzzle[zeroNode.x][zeroNode.y].value;
                    temp.puzzle[zeroNode.x][zeroNode.y].value = possibleSwaps.get(i).value;
                    temp.puzzle[possibleSwaps.get(i).x][possibleSwaps.get(i).y].value = prev;
                }
            }
        }
        //prints out the 2d array that should be the same everytime.  But isn't
        printPuzzle(cur.puzzle);
    }

打印输出示例:

(我想要的原始2d数组)

1   2   3   
4   6   8   
7   []  5   

(切换[]和6,我需要[]保持原来在前一次迭代中的位置,所以它可以在下一次迭代中与5和7交换)

1   2   3   
4   []  8   
7   6   5   

(保留在前一次迭代中交换的位置)

1   2   3   
4   []  8   
7   5   6   

1   2   3   
4   []  8   
5   7   6

0 个答案:

没有答案
相关问题