当我将一个二维数组复制到另一个临时数组中时,当我对临时数组执行操作时,它会更改我的原始数组。
这是我的代码的一部分来说明我的意思:
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()
在我使用它的另一个程序中工作,但在这个程序中不起作用。
任何帮助是极大的赞赏。
还有一件事:
这是家庭作业的一部分。然而,解决这个小问题甚至不会让我接近我需要的最终产品。到目前为止,这只是我代码的一小部分,但我需要克服这一点才能继续。
最佳答案
您需要进行深层复制。
而不是:
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);
}
关于java - 为什么将一个数组复制到另一个数组会改变原始数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12837356/