Java的Arrays.sort(测试)排序两个数组 [英] Java Arrays.sort(test) sorts two arrays

查看:212
本文介绍了Java的Arrays.sort(测试)排序两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已开始在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 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.

这篇关于Java的Arrays.sort(测试)排序两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆