小编典典

如何使用自定义比较器对整数数组进行排序?

java

我需要使用自定义比较器对整数数组进行排序,但是Java的库没有为带有比较器的整数提供排序功能(比较器只能与对象一起使用)。有没有简单的方法可以做到这一点?


阅读 427

收藏
2020-03-24

共1个答案

小编典典

如果你无法更改输入数组的类型,则将执行以下操作:

final int[] data = new int[] { 5, 4, 2, 1, 3 };
final Integer[] sorted = ArrayUtils.toObject(data);
Arrays.sort(sorted, new Comparator<Integer>() {
    public int compare(Integer o1, Integer o2) {
        // Intentional: Reverse order for this demo
        return o2.compareTo(o1);
    }
});
System.arraycopy(ArrayUtils.toPrimitive(sorted), 0, data, 0, sorted.length);

这可以使用ArrayUtilscommons-lang项目轻松地在int[]和之间进行转换Integer[],创建数组的副本,进行排序,然后将排序后的数据复制到原始数据上。

2020-03-24