Reputation: 119
int[] a = new int[] {7,2,1,10,8,9};
int[] b = a;
Arrays.sort(b);
Why do both arrays get sorted after the sort-operation on b. Shouldn't be only b get sorted?
Upvotes: 2
Views: 109
Reputation: 3059
Both b
and a
point to the same array object. So they both are same array.
Upvotes: 0
Reputation: 6882
Because it is only one array. "a" and "b" are only references to the same array.
If you would use the clone method to copy the values, then a and b would be different arrays and only b would be sorted.
Upvotes: 7
Reputation: 21863
Because a
and b
are references to the same array. When you do
int[] b = a;
you're not making a copy of your array, you're just copying a reference to the same array.
Upvotes: 2
Reputation: 16351
Because assigning a to b only assigns reference to the array. There is only one array in memory, so altering it alters it wherever you access it from.
Upvotes: 0