2012-10-11 31 views
2

当我将2D数组复制到不同的临时数组中时,它会在对临时数据执行操作时更改我的原始数组。为什么将数组复制到另一个数组会更改原始数组?

这里是我的代码的一部分来说明我的意思:

public int getPossibleMoves(int color, int turn) { 
    int x = 0; 
    int blankI; 
    blankI = -1; 
    int pBoard[][]; 
    pBoard = new int[board.length][board.length]; 
    System.arraycopy(board, 0, pBoard, 0, board.length); 

    //if its the first turn and color is black, then there are four possible moves 
    if(turn == 0 && color == BLACK) {  
    pBoard[0][0] = BLANK; 
    current.addChild(pBoard); 
    current.children.get(x).setParent(current); 
    System.arraycopy(board, 0, pBoard, 0, board.length); 
    x++; 

    pBoard[pBoard.length-1][pBoard.length-1] = BLANK; 
    current.addChild(pBoard); 
    current.children.get(x).setParent(current); 
    System.arraycopy(board, 0, pBoard, 0, board.length); 
    x++; 

    pBoard[pBoard.length/2][pBoard.length/2] = BLANK; 
    current.addChild(pBoard); 
    current.children.get(x).setParent(current); 
    System.arraycopy(board, 0, pBoard, 0, board.length); 
    x++; 

    pBoard[(pBoard.length/2)-1][(pBoard.length/2)-1] = BLANK; 
    current.addChild(pBoard); 
    current.children.get(x).setParent(current); 
    System.arraycopy(board, 0, pBoard, 0, board.length); 
    x++; 
    } 

在那说pBoard[0][0] = BLANK;和类似的人行了,它改变了板以及pBoard,我需要板上留我的程序正常工作也一样。

我发现了一个类似于此的答案,这是我的想法使用System.arraycopy()而不是pBoard = board的想法。 System.arraycopy()在我使用它的一个不同的程序中工作,但不在这个程序中。
任何帮助,不胜感激。

一件事:
这是一个家庭作业的一部分。但是,解决这个小问题甚至不会使我接近我需要的最终产品。到目前为止,这只是我的一小部分代码,但我需要通过这个继续前进。

+3

看起来你是复制引用,并没有反对。这是浅拷贝 – RNJ

+0

'int's是原语,而不是“通过引用复制” –

+0

我很怀疑这个代码以任何方式修改'board',也许在你的代码中的其他地方? –

回答

1

int board[][]是对int[]类型的数组的引用的数组。 System.arraycopy(board, 0, pBoard, 0, board.length)复制引用数组,但不引用现在可以通过两种方式访问​​的数组。要进行深度复制,您还必须复制所引用的一维数组。请注意,要制作数组的副本,您可以使用array.clone()。还考虑使用大小为N * N的一维数组,访问权限为array[x+N*y]

+0

感谢您的回答!我会给那一枪。 –

3

您需要进行深层复制。

相反的:

pBoard = new int[board.length][board.length]; 
System.arraycopy(board, 0, pBoard, 0, board.length); 

尝试:

pBoard = new int[board.length][]; 
for (int i = 0; i < pBoard.length; i++) { 
    pBoard[i] = new int[board[i].length]; 
    System.arraycopy(board[i], 0, pBoard[i], 0, board[i].length); 
} 
+0

非常感谢你!我做了类似的事情,它的工作完美。 –

相关问题