排序int数组按降序排列 [英] Sorting int array in descending order

查看:241
本文介绍了排序int数组按降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/215271/sort-arrays-of-primitive-types-in-descending-order">Sort原始类型的递减顺序
阵列   <一href="http://stackoverflow.com/questions/1354326/java-how-to-sort-an-array-of-floats-in-reverse-order">Java :如何排序花车以相反的顺序数组
?   我如何扭转Java的一个int数组?

Possible Duplicate:
Sort arrays of primitive types in descending order
Java : How to sort an array of floats in reverse order?
How do I reverse an int array in Java?

随着code升序排序数组

Following code sort the array in ascending order

int a[]={30,7,9,20};
Arrays.sort(a);
System.out.println(Arrays.toString(a));

我要排序的降序排列。如何使用比较?

I need to sort it in descending order. How to use Comparator?

请帮助。

推荐答案

有关基本数组类型,你就必须写一个反向排序算法:

For primitive array types, you would have to write a reverse sort algorithm:

另外,您也可以将您的 INT [] 整数[] ,写一个比较:

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

或使用 Col​​lections.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屋!

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