我想按降序排序priorities[]
,即...2,1,0
。当我执行下面提供的代码时,我收到未排序的数组,例如
18, 14, 15, 19, 23, 37, 35, 1, 8, 24, 26, 36
为什么会这样?
double[] priorities = new double[10];
for (int i = 0; i < 10; i++)
priorities[i] = Math.round(10*Math.random();
ArrayIndexComparator comparator = new ArrayIndexComparator(priorities,1);
Integer[] sortedPriorities = comparator.createIndexArray();
Arrays.sort(sortedPriorities, comparator);
public class ArrayIndexComparator implements Comparator<Integer>
{
private final double[] array;
private int sort;
public ArrayIndexComparator(double[] array, int sort)
{
this.array = array;
this.sort = sort;
}
public Integer[] createIndexArray()
{
Integer[] indexes = new Integer[array.length];
for (int i = 0; i < array.length; i++)
{
indexes[i] = i;
}
return indexes;
}
@Override
public int compare(Integer index1, Integer index2)
{
if (sort == 0)
return Double.compare(array[index2],array[index1]); // ascending order 0,1,2,...
else
return Double.compare(array[index1],array[index2]); // descending order ...2,1,0
}
}
答案 0 :(得分:5)
使用调试器会告诉您比较器无法正常工作的原因。好像你过分复杂了。所有比较器应该采取两个元素,比较它们并返回一个满足您订购要求的结果。
你正在寻找能够有效逆转自然&#34;的比较器。双打的顺序,所以尝试沿着这条线:
double[] priorities = new double[10];
for (int i = 0; i < priorities.length; i++)
priorities[i] = Math.round(10*Math.random());
Arrays.sort(priorities, new ArrayIndexComparator());
...
...
public class ArrayIndexComparator implements Comparator<Double> {
@Override
public int compare(Double d1, Double d2) {
return -1*d1.compareTo(d2);
}
}
(简而言之。你应该把ArrayIndexComparator
变成一个单身,但这超出了这个问题的范围)
如果您懒得这样做,可以下载Commons-Collections并使用内置的反向比较器:
Arrays.sort(priorities, ComparatorUtils.reversedComparator(
ComparatorUtils.naturalComparator()));
然后你甚至不需要自己的自定义比较器类。