epe*_*leg 3 java sorting collections
我有一个[]有一些数字(距离某个点).
我想在第一个数组中创建一个索引数组,其中索引按距离排序.
例如
假设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]);
}
});
Run Code Online (Sandbox Code Playgroud)
但是我得到了几个错误,其中最"有问题的"是:" 不能引用在不同方法中定义的内部类中的非最终变量距离 "
谢谢
Don*_*oby 14
你走在正确的轨道上,但是
Integer数组而不是int数组Comparator<Integer>.Arrays.sort而不是Collections.sort排序数组.如果在匿名内部类中引用,则必须使距离变量为final.
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]);
}
});
Run Code Online (Sandbox Code Playgroud)