比较器的使用

1.在类中添加一个专属类的比较器:

假设已有一个类Student,且有一个int型数据id,按照id的升序构造一个比较器:

public static class IdAscComparator implements Comparator<Student> {
        /*
         * 如果返回的值为负数,则第一个值排前面
         * 如果返回的值为正数,则第二个值排前面
         * 如果返回的值为0,则无所谓谁排前面
         */
        public int compare(Student o1, Student o2) {
            return o1.id - o2.id;
        }
    }

 

2.将默认的升序改为降序:

如将默认的小根堆转为大根堆:

1 /*
2      * 还可以添加一个比较器,使得优先队列从默认的小根堆变为大根堆
3      */
4     public static class IntDescComparator implements Comparator<Integer> {
5         public int compare(Integer o1,Integer o2) {
6             return o2 - o1;
7         }
8     }

 

posted @ 2022-04-07 16:31  jue1e0  阅读(196)  评论(0)    收藏  举报