eppej
eppej

Reputation: 119

Strange sorting behavior

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

Answers (4)

Evelie
Evelie

Reputation: 3059

Both b and a point to the same array object. So they both are same array.

Upvotes: 0

Udo Klein
Udo Klein

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

alestanis
alestanis

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

xlecoustillier
xlecoustillier

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

Related Questions