I recently stumbled across a problem with passing a 2D array by reference to another.
Suppose we have a 2D array (A) and we create a similar 2D array (B). For some reason, it seems as though the changes in B are automatically applied to A.
I have looked into other posts where they mentioned the idea of cloning an array, but that still did not work. I have also created multiple instances of 2D arrays and assigned it to the original. Even then my second array (which I want to be identical to my original yet independent from the original) always happens to affect the original.
Therefore, how can I make the reference of my second array identical to my array but independent from that of my original, such that a change in my second array does not affect my first?
Here is some sample code of the problem (you may assume the board class is also a Square 2D array, defined earlier somewhere):
I have created a new Square 2D array and copied element by element but the issue of reference still persists.
Square [][] board2 = new Square[3][3];
for(int i = 0; i < board2.length; i++){
for(int j = 0; j < board2[0].length; j++)
board2[i][j] = board[i][j];
}
try {
for (int i = 0; i < board.length; i++) {
if (board[i][0].isEmpty() && board[i][1].isEmpty() && board[i][2].isEmpty()) {
board[i][0].Empty();
board[i][1].Empty();
board[i][2].Empty();
}
}
} catch (IndexOutOfBoundsException e) {}
try {
for (int j = 0; j < board2.length; j++) {
if (board2[0][j].isEmpty() && board2[1][j].isEmpty() && board2[2][j].isEmpty()) {
System.out.println("weird this should not happen");
board2[0][j].Empty();
board2[1][j].Empty();
board2[2][j].Empty();
}
}
} catch (IndexOutOfBoundsException e) {}