如何使用自定义比较器对int数组进行排序?
问题描述:
我需要使用自定义比较器对int数组进行排序,但Java库不为带有比较器的int提供排序函数(比较器只能用于对象)。有没有简单的方法呢?
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
可轻松转换 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.