Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java method "Arrays.copyOf" behaviour is not the same when it deals with an array of integers in compared to an array of objects

Tags:

java

arrays

I copied an array of integers to another array using method Arrays.copyOf. 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 also 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" 
like image 636
Tariq Sayed Avatar asked Mar 17 '23 11:03

Tariq Sayed


1 Answers

You copy references to the objects, not the objects (you'd need to clone them to get what you think you want).

With primitives (eg. int), there's no such thing as "reference", they are just numbers. So you copy the numbers.

Similar would apply to immutables like Integer or String - there it copies reference, but since the numbers (or String) are immutable, you'd get the same result.

like image 71
MightyPork Avatar answered Apr 06 '23 04:04

MightyPork