4

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" 
  • Because Java passes by value, always, even if the value is a reference - The reference will be passed, by value.. So when you change the value, which is a reference, you're actually changing a reference. – Maroun Jan 03 '15 at 12:33
  • 5
    The behavior is *exactly* the same. An array of `int` contains `int` values. An array of `Person` contains `Person` *references*. In both cases the contents are copied. – Hot Licks Jan 03 '15 at 13:27

3 Answers3

6

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.

MightyPork
  • 18,270
  • 10
  • 79
  • 133
1

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

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

Community
  • 1
  • 1
Nilanjan Basu
  • 828
  • 9
  • 20
0

That's because when you call copyOf, it copies the same reference of the object (person in your case) in the newly allocated array. So when you change one you get to see the same in the other as well.

While your first example deals with primitives rather than objects.

SMA
  • 36,381
  • 8
  • 49
  • 73