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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With