0

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) {}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • In Java, an array is a reference type. `Square [][] board2 = board` creates an alias -- `board2` and `board` reference the same array. If you want `board2` to begin its life independent from `board`, but with the same elements, you need to copy the elments. – Old Dog Programmer Mar 31 '23 at 02:44
  • @OldDogProgrammer Thank you, I will give it a try and update accordingly. – Josue Arreaga Mar 31 '23 at 02:46
  • 1
    [This thread](https://stackoverflow.com/questions/9106131/how-to-clone-a-multidimensional-array-in-java) should be helpful – Calvin P. Mar 31 '23 at 02:48
  • We don't see the code for `Square`, but it's not a primitive, so it must be a reference type. So, `board2[i][j] = board[i][j];` results in a 2D array of aliases. If `Square` doesn't already have a copy constructor, add one. That will allow code like `board2[i][j] = new Square (board[i][j]);`. An alternative is to have a copy method in `Square`: `board[i][j] = board[i][j].copyOf ();` – Old Dog Programmer Mar 31 '23 at 03:39
  • By the way, Java doesn't have true 2D arrays. It allows arrays of reference types, and an array is a reference type. So, what looks like a 2D array can be described as a nested array. One result is that rows in an array can have different lengths. So, the inner `for` in the code to copy would be better as `for(int j = 0; j < board2[i].length; j++)`. – Old Dog Programmer Mar 31 '23 at 03:45

1 Answers1

0

The behavior you're encountering is an effect of how references work in general. Two variables with the same reference will point to the same data in memory, so modifying that memory affects the value you get from any variable holding the same reference. This also applies to nested arrays.

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?

This is impossible, since propagating changes is a behavior of references as a whole. You need to deeply clone the arrays as described in this answer to have a completely new array with the same contents, and clone the Square instances to have those independant from the original as well.

That_Guy977
  • 101
  • 5