有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java数组。sort(test)对两个数组进行排序

我在Java中启动了一个数组,使其与另一个数组相同。我这样做是因为我只想对数组的副本排序,而不是对原始数组排序。这可以很好地工作,因为新数组中填充了原始值。当我对数组进行排序时,问题就出现了。原稿也会被分类。所以我的原著也被分类了。如何更正此错误,以便只对数组的副本进行排序

double[] distancesSort = distances;
Arrays.sort(distancesSort);

共 (1) 个答案

  1. # 1 楼答案

    =不用于将一个数组的元素复制到另一个数组中

    使用

    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.

    参数:

    arr - the array to be copied
    length - the length of the copy to be returned

    返回:

    a copy of the original array, truncated or padded with zeros to obtain the specified length

    如果使用=,那么distancesSort将引用distancesdistancesSort中的任何变化也将反映distances中的变化