當我將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()
在我使用它的一個不同的程序中工作,但不在這個程序中。
任何幫助,不勝感激。
一件事:
這是一個家庭作業的一部分。但是,解決這個小問題甚至不會使我接近我需要的最終產品。到目前爲止,這只是我的一小部分代碼,但我需要通過這個繼續前進。
看起來你是複製引用,並沒有反對。這是淺拷貝 – RNJ
'int's是原語,而不是「通過引用複製」 –
我很懷疑這個代碼以任何方式修改'board',也許在你的代碼中的其他地方? –