【问题标题】:Why does copying an array into another array change the original array?为什么将一个数组复制到另一个数组会改变原始数组?
【发布时间】:2012-10-11 10:20:40
【问题描述】:

当我将二维数组复制到不同的临时数组中时,当我对临时数组执行操作时,它会更改我的原始数组。

这是我的代码的一部分,以说明我的意思:

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

还有一件事:
这是家庭作业的一部分。然而,解决这个小问题甚至不会让我接近我需要的最终产品。到目前为止,这只是我代码的一小部分,但我需要克服它才能继续前进。

【问题讨论】:

  • 看起来您正在复制引用而不是对象。这是浅拷贝
  • ints 是原语,而不是“通过引用复制”
  • 我非常怀疑这段代码是否以任何方式修改了board,也许在您代码的其他地方?
  • 我使用了 netbeans 调试器,当它通过 pBoard[0][0] = BLANK;线。顺便说一下,BLANK = -1。

标签: java arrays multidimensional-array


【解决方案1】:

你需要做一个深拷贝。

代替:

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

【讨论】:

  • 非常感谢!我做了类似的事情,而且效果很好。
【解决方案2】:

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

【讨论】:

  • 感谢您的回答!我会试一试。
猜你喜欢
  • 2011-05-12
  • 2020-03-12
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
相关资源
最近更新 更多