關於Comparator的自定義排序

這個問題,必須要做一波筆記了。。。。。因爲總是記不清

升序:

// 02 01 01>02
if(o1>o2)  return 1; //不交換順序

降序:

// 02 01 01>02
if(o1>o2)  return -1; //(交換順序)
//對數組的頭進行升序排序
Arrays.sort(intervals, new Comparator<int[]>() {
    /**
     * 默認升序排序 o2在前,01在後
     * 如果返回1,代表不交換順序
     * 如果返回-1,代表交換順序
     */
    @Override
    public int compare(int[] o1, int[] o2) {
        return o1[0]-o2[0];
    }
});
//對數組的頭進行降序排序
Arrays.sort(intervals, new Comparator<int[]>() {
    /**
     *
     * 默認升序排序 o2在前,01在後
     * 如果返回1,代表不交換順序
     * 如果返回-1,代表交換順序
     */
    @Override
    public int compare(int[] o1, int[] o2) {
        return o2[0]-o1[0];
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章