Reputation: 509
I have initiated an array in Java to be the same as another array. I have done this because I only want to sort a copy of the array not the original. This works fine the new array is filled with the original values. The problem then arises when I sort the array. The original also gets sorted. So my original is also sorted. How do I correct this so that only the copy of the array gets sorted.
double[] distancesSort = distances;
Arrays.sort(distancesSort);
Upvotes: 1
Views: 231
Reputation: 4534
=
is not used to copy elements of one array into another.
Use
double[] distancesSort = Arrays.copyOf(distances,distances.length);
Arrays.copyOf(double[] arr, int length)
Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain 0L. Such indices will exist if and only if the specified length is greater than that of the original array.
Parameters:
arr - the array to be copied
length - the length of the copy to be returned
Returns:
a copy of the original array, truncated or padded with zeros to obtain the specified length
If you use =
then distancesSort
will refer to distances
. Any changes in distancesSort
will reflect the changes in distances
also.
Upvotes: 14