Unable to copy my object and change values

I am having problems copying an object to use and changing the values ​​for this copy, instead it changes the values ​​for both of my objects. Code for the object.

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

And the code for the function I was trying to work with

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

Therefore, when I try to insert the value 1 into a new object, the old one is still changing.

+6
source share
3 answers
 public Board(int[][] layout){ board = layout; } 

This will make the panel and layout point the same address. Try something like:

 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]; } 
+3
source

When you assign an array variable to an existing array, you are not getting a new array. You get two references to the same array.

For instance:

 int[] a = { 1, 2, 3}; int[] b = a; 

a and b are not two arrays, but two references to the same array. Subsequently, the change in a coincides with the change in b .

With 2D arrays, there is another catch: the int[][] x array is actually an array containing a sequence of other arrays. Therefore, a naive copy of it ( int[][] y = x.clone() ) will give you two int[][] arrays containing general references to the sequence of int[] arrays.

To correctly copy a 2D array, you must copy the individual 1D arrays inside it.

-

In your case, both objects contain references to the same array. If you want them to have separate arrays, you need to copy the array. You can copy the array in the constructor as follows:

 public Board(int[][] layout) { board = new int[layout.length][]; for (int i = 0; i < layout.length; ++i) { board[i] = layout[i].clone(); } } 
+2
source

You also need to copy the layout array.

 public Board copy(Board b) { Node node = new Node(b); int[][] oldLayout = node.getBoard().getBoard(); int[][] newLayout = new int[9][9]; for(int i=0; i<newLayout.length; i++) { newLayout[i] = Arrays.copyOf(oldLayout[i], oldLayout[i].length); } Board temp = new Board(newLayout); temp.insertValue(1,4,5); return temp; } 
+1
source

Source: https://habr.com/ru/post/980339/


All Articles