如何使用自定义比较器对整数数组进行排序? [英] How to sort an array of ints using a custom comparator?

查看:31
本文介绍了如何使用自定义比较器对整数数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to sort an array of ints using a custom comparator, but Java's library doesn't provide a sort function for ints with comparators (comparators can be used only with objects). Is there any easy way to do this?

推荐答案

如果您无法更改输入数组的类型,则以下内容将起作用:

If you can't change the type of your input array the following will work:

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);

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

This uses ArrayUtils from the commons-lang project to easily convert between int[] and Integer[], creates a copy of the array, does the sort, and then copies the sorted data over the original.

这篇关于如何使用自定义比较器对整数数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆