Kla*_*sos 0 java sorting comparable comparator
我想priorities[]按降序排序,即...2,1,0.当我执行下面提供的代码时,我收到未排序的数组,例如
18, 14, 15, 19, 23, 37, 35, 1, 8, 24, 26, 36
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
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
}
}
Run Code Online (Sandbox Code Playgroud)
使用调试器会显示比较器不起作用的原因.好像你过分复杂了.所有比较器应该做的是采取两个元素,比较它们并返回一个满足您订购要求的结果.
你正在寻找一个有效地逆转双打的"自然"顺序的比较器,所以尝试一下以下方面:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
(简而言之.你应该真的ArrayIndexComparator变成一个单身人士,但这超出了这个问题的范围)
如果你太懒了,你可以下载Commons-Collections并使用内置的反向比较器:
Arrays.sort(priorities, ComparatorUtils.reversedComparator(
ComparatorUtils.naturalComparator()));
Run Code Online (Sandbox Code Playgroud)
然后你甚至不需要自己的自定义比较器类.