按降序对int数组进行排序 [英] Sorting int array in descending order
本文介绍了按降序对int数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
按降序对原始类型数组进行排序
Java:如何对浮点数组进行排序逆序?
如何在 Java 中反转 int 数组?
以下代码将按升序顺序对数组进行排序:
The following code will sort the array in ascending order :
int a[] = {30,7,9,20};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
我需要按降序排序.我如何使用 Comparator 来做到这一点?
I need to sort it in descending order. How do I use Comparator to do this?
请帮忙.
推荐答案
对于原始数组类型,您必须编写反向排序算法:
For primitive array types, you would have to write a reverse sort algorithm:
或者,您可以将 int[]
转换为 Integer[]
并编写一个比较器:
Alternatively, you can convert your int[]
to Integer[]
and write a comparator:
public class IntegerComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}
或使用 Collections.reverseOrder()
因为它只适用于非原始数组类型.
or use Collections.reverseOrder()
since it only works on non-primitive array types.
最后,
Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());
//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);
这篇关于按降序对int数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文