Arrays.sort()如何实现从大到小排序
Java中的Arrays.sort()方法默认将数组元素从大到小排序. 要实现从大到小排序java也提供了一种方法:
Arrays中的sort(T[] a, Comparator<?super T> c),
但是传入的数组类型不能是基本类型(int char double),只能使用对应的类(Integer),因为Comparator接口中的
compare()方法默认从小到大排序,我们只需要重写这个方法就行了.下面是测试demo。
public class SortTest { public static void main(String[] args) { Integer[] arr = {4, 6, 3, 9, 1, 5, 8}; Comparator<Integer> c = new Mycomparator(); // 实例化一个Comparator对象 Arrays.sort(arr, c); for(Integer ele : arr) { System.out.print(ele +" "); } } // 运行后是从大到小排好序的 } class Mycomparator implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { if(o1 > o2) // 默认是o1 < o2时返回-1, 一下同理 return -1; if(o1 < o2) return 1; return 0; } }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。