Java中sort實現降序排序


利用Collections的reverseOrder方法:

import java.util.Arrays;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
        Arrays.sort(arr, Collections.reverseOrder());
        for (Integer x : arr) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
}

利用Comparator接口復寫compare方法:

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        //注意,要想改變默認的排列順序,不能使用基本類型(int,double, char),而要使用它們對應的類
        Integer[] arr = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
        //定義一個自定義類MyComparator的對象
        Comparator cmp = new MyComparator();
        Arrays.sort(arr, cmp);
        for (int x : arr) {
            System.out.print(x + " ");
        }
    }
}

//實現Comparator接口
class MyComparator implements Comparator<Integer> {
    @Override //作用是檢查下面的方法名是不是父類中所有的,也起到注釋的作用
    public int compare(Integer a, Integer b) {
        return a > b ? -1 : 1;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM