为什么复制数组到另一个数组改变原来的数组? [英] Why does copying an array into another array change the original array?

查看:172
本文介绍了为什么复制数组到另一个数组改变原来的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我复制一个二维数组到一个不同的临时数组,这时候我就临时执行操作改变我原来的。

When I copy a 2D array into a different temporary array, it changes my original when I perform operations on the temporary.

这里是展示一下我的意思是我的code的一部分:

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] =空; 和类似的,它改变电路板以及 pBoard ,我需要板上留我的程序正常工作一样。

On the line that says pBoard[0][0] = BLANK; and the similar ones, it changes board as well as pBoard and I need board to stay the same for my program to work correctly.

我发现类似这样的一个答案,这是我得到了主意,用 System.arraycopy()而不是 pBoard =板。在 System.arraycopy()工作在不同的程序,我用它,但不是在这一个。结果
任何帮助是极大的AP preciated。

I have found an answer similar to this, which is where I got the idea to use System.arraycopy() instead of pBoard = board. The System.arraycopy() works in a different program that I used it in, but not in this one.
Any help is greatly appreciated.

一件事:结果
这是一个家庭作业的一部分。但是,解决这个问题的小甚至不会给我带来接近最终产品,我需要的。这是我的code的只是一个很小的一块,到目前为止,但我需要得到过去,这继续前进。

One more thing:
This is part of a homework assignment. However, solving this small issue will not even bring me close to the final product that I need. This is just a tiny chunk of my code so far, but I need to get past this to move on.

推荐答案

您需要做的深层副本。

而不是:

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

这篇关于为什么复制数组到另一个数组改变原来的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆