Suppose we have an array of three integers in array2 , and somehow we initialize it.

 int[] array2 = new int[3]; array2[0] = 0; array2[1] = 3; array2[2] = 5; 

Create its clone and collect all values ​​from array2 .

 int[] array3 = new int[3]; array3 = array2; 

Its values ​​are starting to change ...

 array3[0] = 1; array3[1] = 2; array3[2] = 3; 

And, debugging, with horror we find out that the values ​​of array3 = {1,2,3} and array2 for some reason also became {1,2,3} instead of the proper ones {0,3,5}

How to make the memory areas that are referenced by both arrays become different from each other and how do you set variables in this case?

  • You assigned a link to array2 to array3, and for this link are the values ​​of array2 - georgehardcore
  • Suppose this link, but how to make the objects become independent? - Kiryl Aleksandrovich
  • already answered below georgehardcore

1 answer 1

In line:

 array3 = array2; 

link array2 copied to object array3 . Therefore, after executing this line, array2 and array3 will refer to the same memory area.

You can copy the values ​​themselves, for example, like this:

 System.arraycopy(array2, 0, array3, 0, array2.length); 

You can also use Arrays.copyOf(...) , Object.clone() or copying the elements of one array into another in a loop (here it is possible, since a given array stores elements of a primitive type ).