比较器

比较器

PriorityQueue&自定义类比较器使用

思路来源

一周刷爆LeetCode,算法大神左神(左程云)耗时100天打造算法与数据结构基础到

笔记内容

  • 问题描述

    1. 比较器作用:重载比较运算符
    2. 比较器默认规则:返回负数第一个参数排前面;返回正数第二个参数拍前面
  • 代码实现

    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.PriorityQueue;
    
    public class MyComparer {
        public static class SortByStandA implements Comparator<Test>{
            @Override
            public int compare(Test o1, Test o2) {
                return o1.standA - o2.standA; //升序
            }
        }
    
        public static class Dagendui implements Comparator<Integer>{
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        }
    
        public static void main(String[] args) {
            /**
             * 自定义类比较器
             * */
            Test a = new Test("aa",10,56);
            Test b = new Test("bb",5,44);
            Test c = new Test("cc",78,98);
            Test[] temp = {a,b,c};
            Arrays.sort(temp,new SortByStandA());
    
            for (int i = 0; i < temp.length; i++) {
                System.out.println(temp[i]);
            }
    
            //大根堆
            PriorityQueue<Integer> temp = new PriorityQueue<>(new Dagendui());
            temp.add(1);
            temp.add(5);
            temp.add(7);
            temp.add(9);
            temp.add(6);
            temp.add(2);
            while (!temp.isEmpty()){
                System.out.println(temp.poll());
            }
    
        }
    }
    
    class Test{
        public String name;
        public int standA;
        public int standB;
    
        public Test(String name, int standA, int standB) {
            this.name = name;
            this.standA = standA;
            this.standB = standB;
        }
    
        @Override
        public String toString() {
            return "Test{" +
                    "name='" + name + '\'' +
                    ", standA=" + standA +
                    ", standB=" + standB +
                    '}';
        }
    }
    
    
posted @ 2023-12-20 13:00  Noule  阅读(6)  评论(0编辑  收藏  举报