我在制作要使用的对象的副本并更改该副本的值时遇到问题,而是更改了我的两个对象的值.对象的代码.
public class Board {
private int[][] board;
public Board() {
board = new int[9][9];
}
public Board(int[][] layout){
board = layout;
}
public int[][] getBoard(){
return board;
}
public int getBoardValue(int y, int x){
return board[y][x];
}
public void insertValue(int v, int y, int x){
board[y][x] =v;
}
}
Run Code Online (Sandbox Code Playgroud)
以及我一直试图开始工作的函数的代码
public Board copy(Board b) {
Node node = new Node(b);
int[][] layout = node.getBoard().getBoard();
Board temp = new Board(layout);
temp.insertValue(1,4,5);
return temp;
}
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试在新对象中插入值1时,旧对象仍会更改.
public Board(int[][] layout){
board = layout;
}
Run Code Online (Sandbox Code Playgroud)
这使得电路板和布局指向同一地址。尝试类似的方法:
public Board(int[][] layout){
this();
for(int i=0; i<layout.length;i++)
for(int j=0; j<layout[0].length;j++)
board[i][j] = layout[i][j];
}
Run Code Online (Sandbox Code Playgroud)