Why Java's "Arrays.copyOf" method behaves differently than when it deals with an array of integers versus an array of objects

I copied an array of integers to another array using the Arrays.copyOf method. If I change an element in one of the array, the corresponding member does not change accordingly.

But when I copied an array of objects to another array of objects using the same method. And I change an element in one of the array, the corresponding member changes accordingly.

Can someone explain why the behavior is different in both cases.

Example: array of strings

int[] array1 = {1,2,3};

int[] array2 = Arrays.copyOf(array1, array1.length);

array1[1] = 22;   // value of array2[1] is not set to 22

array1[2] = 33;   // value of array1[2] is not set to 33

      

Example: array of objects

Person[] AllPersons = new Person[3];

for(int i=0; i<3; i++) 
{
  AllPersons[i] = new Person();
}

AllPersons[2].Name = "xyz";

Person[] OtherPersons  =  Arrays.copyOf(AllPersons, 3);  // value of OtherPersons[2].Name is also set to "xyz"

AllPersons[2].Name = "pqr";    // value of OtherPersons[2].Name is also set to "pqr" 
OtherPersons[2].Name = "hij";   // value of AllPersons[2].Name is also set to "hij" 

      

+3


source to share


3 answers


You are copying object references, not objects (you need to clone them to get what you see fit).

With primitives (eg int

), there is no such thing as a "link", it's just numbers. This way you copy the numbers.



Likewise applies to immutable types Integer

or String

- there it copies the reference, but since numbers (or Strings) are immutable, you'll get the same result.

+5


source


This is because the copy of the original array is a shallow copy. Hence the copied array consists of references when the contents of those arrays were objects. For arrays with primitives (in this case, an integer) there is no reference, the values ​​themselves are copied.



See: Does Arrayys.copyOf produce a shallow or deep copy?

+1


source


This is because when you call copyOf it copies the same object reference (person in your case) into the newly allocated array. Therefore, when you change one, you also see the same in the other.

Whereas your first example is about primitives, not objects.

0


source







All Articles