0

I would like to understand what array = array actually does.

Why does editing data1 leads to data2 being changed later on in the process?

String[][] data1 = new String[5][1];
String[][] data2 = new String[1][1];

data1[0][0] = "Test 1";
data2 = data1;

//Prints "Test 1"
System.out.println(data2[0][0]);

data1[0][0] = "NEW";

//Prints "NEW"
System.out.println(data2[0][0]);
X3Gamma
  • 105
  • 9
  • 1
    `data2 = data1;`. Both `data2` and `data1` refer to the same array (`new String[5][1]`) – Thiyagu Jul 24 '18 at 17:50
  • I haven't done Java in a long time but I think this only works because the data type for both are the same. If let's say `data2` wasn't a 2-dimensional array of strings then `data2 = data1` will error out. – dokgu Jul 24 '18 at 17:52
  • This is easier to understand in the C language where an array is actually the address of the first element of the array. `data2 = data1` actually make both variables point to the same array. – Arnaud Denoyelle Jul 24 '18 at 17:58

3 Answers3

1
data2 = data1;

At 4th line, you order that data1 will refer to where data2 refer to from now on. So, both references refer to same object. Any modification by using one of the references will be seen by each other. That's what = operator actually does in Java. Technically, it is reference copying in this way.

  • Questions like this show that operator overloading is a *bad* idea. Glad Java doesn't have it. – M. le Rutte Jul 24 '18 at 17:57
  • @M.leRutte It depends. Just because one needs to be careful when overloading operators doesn't mean that operator overloading is a bad thing; it just means that one should do it with care and only where it makes sense. That's my two cents at least. – Soner from The Ottoman Empire Jul 24 '18 at 18:01
1

In Java, the array name actually holds the starting address of the array (similar to c/c++). The array index is the offset form the starting address.

So, when you use array2 = array1, you are essentially telling the compiler:

"Let array2 hold the same address as array1"

Susmit Agrawal
  • 3,649
  • 2
  • 13
  • 29
0

As already mentioned in the previous answers that it refers to the same location when you use the = operator, changes are reflected in both.

If you don't want that then you should use clone the arrays. You can refer this answer on how to do it.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108