zoukankan      html  css  js  c++  java
  • Java排序方法sort的使用详解

    对数组的排序:

    1 //对数组排序
    2 public void arraySort(){
    3     int[] arr = {1,4,6,333,8,2};
    4     Arrays.sort(arr);//使用java.util.Arrays对象的sort方法
    5     for(int i=0;i<arr.length;i++){
    6         System.out.println(arr[i]);
    7     }
    8 }

    对集合的排序:

     1 //对list升序排序
     2     public void listSort1(){
     3         List<Integer> list = new ArrayList<Integer>();
     4         list.add(1);
     5         list.add(55);
     6         list.add(9);
     7         list.add(0);
     8         list.add(2);
     9         Collections.sort(list);//使用Collections的sort方法
    10         for(int a :list){
    11             System.out.println(a);
    12         }
    13     }
    14     //对list降序排序
    15     public void listSort2(){
    16         List<Integer> list = new ArrayList<Integer>();
    17         list.add(1);
    18         list.add(55);
    19         list.add(9);
    20         list.add(0);
    21         list.add(2);
    22         Collections.sort(list, new Comparator<Integer>() {
    23             public int compare(Integer o1, Integer o2) {
    24                 return o2 - o1;
    25             }
    26         });//使用Collections的sort方法,并且重写compare方法
    27         for(int a :list){
    28             System.out.println(a);
    29         }
    30     }<br>注意:Collections的sort方法默认是升序排列,如果需要降序排列时就需要重写conpare方法
  • 相关阅读:
    XAF 如何在工具栏显示多参数
    XAF Study Recources
    常用工具
    Linux下Kill函数用法
    ipv6相关转换
    宣布回归
    微软夏令营
    APEX SDK阅后感
    寻求offer,开始记录我的征程
    衣服模拟结果
  • 原文地址:https://www.cnblogs.com/lwx521/p/7627045.html
Copyright © 2011-2022 走看看