gpt4 book ai didi

java - 自定义排序java数组

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:17 30 4
gpt4 key购买 nike

我有一个 [] 有一些数字(到某个点的距离)。
我想在第一个数组中创建一个索引数组,其中索引按距离排序。

例如

假设 double[] dist=new double[5] {3.2, 1.4, 7.3, 2.2, 9.1};
然后我想得到一个这样的数组:

int[] sortedIndexes=new int[5] {1, 3, 0, 2, 4};

所以如果我想要第二个最近的距离,我可以检查 dist[sortedIndexes[1]]。
我不想对原始数组进行排序,只是根据距离对索引数组进行排序。

更新 1:我尝试的代码如下所示:

Collections.sort(sortedIDXs, new Comparator<Integer>() {
public int compare(int idx1, int idx2) {
return Double.compare(distances[idx1], distances[idx2]);
}
});

但是我遇到了几个错误,其中最“有问题”的是:“无法在不同方法中定义的内部类中引用非最终变量距离

谢谢

最佳答案

你走在正确的轨道上,但是

  • 你最好用 Integer数组比 int数组,如果您使用的是通用 Comparator<Integer> .
  • 你必须使用 Arrays.sort相反 Collections.sort用于对数组进行排序。
  • 如果在匿名内部类中引用 distances 变量,则必须将其设为最终变量。

    final double[] distances=new double[]{3.2, 1.4, 7.3, 2.2, 9.1};
    Integer[] sortedIDXs = new Integer[]{0,1,2,3,4};
    Arrays.sort(sortedIDXs, new Comparator<Integer>() {
    public int compare(Integer idx1, Integer idx2) {
    return Double.compare(distances[idx1], distances[idx2]);
    }
    });

关于java - 自定义排序java数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10471665/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com