Arrays.sort()如何实现从大到小排序

Java中的Arrays.sort()方法默认将数组元素从大到小排序. 要实现从大到小排序java也提供了一种方法:

Arrays中的sort(T[] a, Comparator<?super T> c), 

但是传入的数组类型不能是基本类型(int char double),只能使用对应的类(Integer),因为Comparator接口中的

compare()方法默认从小到大排序,我们只需要重写这个方法就行了.下面是测试demo。


public class Demo1 {

    public static void main(String[] args) {

        Integer[] arr = {4, 6, 3, 9, 1, 5, 8};

        //默认从小到大排序
        // Arrays.sort(arr);

        //从大到小排序
        Arrays.sort(arr, new Demo2());

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

class Demo2 implements Comparator<Integer> {
    /**
     * 从写compare方法,默认从小到大排序,更改后从大到小排序
     *
     * @param o1
     * @param o2
     * @return
     */
    @Override
    public int compare(Integer o1, Integer o2) {
        // 默认是o1 < o2时返回-1, 一下同理
        if (o1 > o2) {
            return -1;
        }
        if (o1 < o2) {
            return 1;
        }
        return 0;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39770927/article/details/88662071