关于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];
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章