自定义排序java数组 [英] custom sorting a java array
问题描述
我有一个[]有一些数字(距某点的距离)。
我想在第一个数组中创建一个索引数组,其中索引按距离排序。
I have an [] that has some numbers (distances from some point).
I want to create an array of indexes into the first array where the indexes are sorted by the distance.
例如
假设 double [] dist = new double [5] {3.2, 7.3,2.2,9.1};
然后我想得到一个这样的数组:
suppose double[] dist=new double[5] {3.2, 1.4, 7.3, 2.2, 9.1};
then I want to get an array like this:
int [] sortedIndexes = new int [5] {1,3,0,2,4};
第二最近的距离我可以检查dist [sortedIndexes [1]]。
我不想排序原始数组,只是基于距离的索引数组。
so if I want the second nearest distance I can check dist[sortedIndexes[1]].
I don't want to sort the original array, just the array of indexes based on the distances.
更新1:
我正在尝试的代码看起来像这样:
UPDATE 1: The Code I was trying looks like this:
Collections.sort(sortedIDXs, new Comparator<Integer>() {
public int compare(int idx1, int idx2) {
return Double.compare(distances[idx1], distances[idx2]);
}
});
但是我遇到了几个错误,最有问题的是:
But I am getting several errors with it with the most "problematic" one being: "Cannot refer to a non-final variable distances inside an inner class defined in a different method"
感谢您使用不同方法定义的内部类中不能引用非最终变量距离
Thanks
推荐答案
您在正确的轨道上,但
- 如果使用
Integer
数组比使用int
数组更好一个通用的Comparator< Integer>
。 - 你必须使用
Arrays.sort
Collections.sort
用于排序数组。 -
匿名内部类。
- You're better off with an
Integer
array than anint
array if you're using a genericComparator<Integer>
. - You have to use
Arrays.sort
insteadCollections.sort
for sorting an array. You have to make the distances variable final if it's referenced in an anonymous inner class.
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数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!