Java的Arrays.sort(测试)排序两个数组 [英] Java Arrays.sort(test) sorts two arrays
问题描述
我已开始在Java中的数组要与另一个相同的数组。我这样做,因为我只是要排序的数组不是原件及复印件。这工作正常新阵列填充有原始值。那么问题就出现了,当我数组排序。原来也将被排序。所以,我原来也来分类的。如何纠正这使得仅该阵列的拷贝被排序。
双击[] = distancesSort距离;
Arrays.sort(distancesSort);
=
不使用一个数组中的元素复制到另一个。
使用
双击[] = distancesSort Arrays.copyOf(距离,distances.length);
Arrays.copyOf(双[]改编,INT长度)
复制指定的数组,截取或用零填充(如
必要),以使副本具有指定的长度。对于所有的指数
都是原始数组和副本中都有效,这两个数组将
包含相同的值。对于在副本中是有效的索引
但不是原来的,副本将包含0L。这样的指数将
存在当且仅当该指定的长度比中的较大
原始数组。
块引用>参数:
改编 - 数组复制结果
长度 - 副本的长度要
返回
块引用>返回:
原数组的副本,截取或用0来获得填补
指定的长度
块引用>如果您使用
=
然后distancesSort
将参照距离
。在distancesSort
的任何更改将反映距离的变化
也。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);
解决方案
=
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 returnedReturns:
a copy of the original array, truncated or padded with zeros to obtain the specified length
If you use
=
thendistancesSort
will refer todistances
. Any changes indistancesSort
will reflect the changes indistances
also.这篇关于Java的Arrays.sort(测试)排序两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!