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 }
通过Arrays中的sort对数组进行从小到大的排序
最新推荐文章于 2024-07-22 08:37:45 发布
该代码示例展示了如何使用自定义Comparator类对Integer数组进行降序排序。通过创建Mycomparator类并重写compare方法,实现了当o1大于o2时返回-1,o1小于o2时返回1,相等时返回0的比较逻辑。最后,Arrays.sort方法结合自定义比较器完成排序,并打印排序后的数组。
摘要由CSDN通过智能技术生成