繁体   English   中英

为什么将一个数组复制到另一个数组会更改原始数组?

[英]Why does copying an array into another array change the original array?

当我将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()在我用过的另一个程序中工作,但在本程序中没有。
任何帮助是极大的赞赏。

还有一件事:
这是家庭作业的一部分。 但是,解决这个小问题甚至无法使我接近所需的最终产品。 到目前为止,这只是我的代码中的一小部分,但是我需要克服这一点才能继续。

您需要做一个深拷贝。

代替:

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);
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM