Java中通过Array.sort()对数组从大到小排序

 1 package com.itheimajavase;
 2 
 3 import java.util.Arrays;
 4 import java.util.Comparator;
 5 
 6 public class Day01 {
 7 
 8     public static void main(String[] args) {
 9 
10         Integer[] arr = {4, 6, 3, 9, 1, 5, 8};
11         Mycomparator c = new Mycomparator();    // 实例化一个Comparator对象
12         Arrays.sort(arr, c);
13         for(Integer ele : arr) {
14             System.out.print(ele +" ");
15         }
16     }
17     // 运行后是从大到小排好序的
18 }
19 class Mycomparator implements Comparator<Integer> {
20     @Override
21     public int compare(Integer o1, Integer o2) {
22         if(o1 > o2) // 默认是o1 < o2时返回-1, 一下同理
23             return -1;
24         if(o1 < o2)
25             return 1;
26         return 0;
27     }
28 }

直接上代码

猜你喜欢

转载自www.cnblogs.com/pengge666/p/11789928.html