当我将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',也许在你的代码中的其他地方? –