Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java Arrays.sort

I am learning about how Arrays.sort(...) works in Java.

Why are variables: temp and dopas both sorted after the only sorting temp?

System.out.println("Before");
for (int i = 0; i < POP; i++)
  System.out.println(dopas[i]+"");           //dopas is unsorted

System.out.println("After");
float[] temp=dopas;
Arrays.sort(temp);                           //sort temp

for (int i = 0; i < POP; i++)
  System.out.println(temp[i]+" "+dopas[i]);  //Both temp and dopas are now sorted

I expected dopas to remain unsorted.

like image 752
czy Avatar asked Aug 29 '11 13:08

czy


2 Answers

Arrays are objects in Java, therefore when using array variables you are actually using references to arrays.

Thus the line

float[] temp=dopas;

will only copy the reference to array dopas. Afterwards, dopas and temp point to the same array, hence both will appear sorted after using sort().

Use System.arrayCopy or Arrays.copyOf to create a copy of the array.

like image 83
sleske Avatar answered Oct 25 '22 10:10

sleske


your assignment: float[] temp=dopas; is actually just copying a reference to the array. What I think you want to do is float[] temp = dopas.clone();

like image 45
Dogmatixed Avatar answered Oct 25 '22 10:10

Dogmatixed