Reputation: 41
I have an Array a1 and a2
What does the code a1=a2; exactly do? Copy all elements in Array a1? That´s what I thought but that does not seem to happen?
No it copies no array elements whatsoever but rather assigns a references. In sum it means that a1 refers to the exact same array object reference as a2 does.
Code:
int[] a1 = new int[] { 1, 2, 3 };
int[] a2 = new int[] { 4, 5, 6 };
a1 = a2;
a1[1] = 3;
a2[2] = 2;
a2 = a1;
for (int i = 0; i < a2.length; i++) {
System.out.print(a2[i] + " ");
}
Can someone explan why the outcome is 4 3 2 and not 4 3 6?
Upvotes: 3
Views: 69
Reputation: 285403
No it copies no array elements whatsoever but rather assigns a references. In sum it means that a1 refers to the exact same array object reference as a2 does.
If you want to copy elements, you could use a for loop, or System.arraycopy(...)
If you want to do a deep copy, then I would use a for loop, and make copies of each of the elements, perhaps with a copy constructor or by cloning, or whatever makes the most sense for the items held by the array.
Edit
Your additional code with my comments:
int[] a1 = new int[] { 1, 2, 3 };
int[] a2 = new int[] { 4, 5, 6 };
a1 = a2; // both array variables refer to the one same array object, 4, 5, 6
a1[1] = 3; // you're changing the one single array's 2nd item
a2[2] = 2; // you're changing the same array's 3rd item
a2 = a1; // this does nothing really as they already refer to the same object
for (int i = 0; i < a2.length; i++) {
System.out.print(a2[i] + " ");
}
So thats why the result is 4 3 2 and not 4 3 6?
Yep, see comments
Upvotes: 4
Reputation: 1954
a1
and a2
are both object references. When you say a1 = a2
, a1
is literally set to the object reference of a2
. This means that a1
and a2
both point to the same object on the heap.
Upvotes: 1
Reputation: 1570
It makes a2 refer to the same array that a1 does.
Only one copy of the array actually exists in memory. This means that if you start changing elements of a1, those changes will show up when you read from a2.
Upvotes: 1