比较器
比较器
PriorityQueue&自定义类比较器使用
思路来源
一周刷爆LeetCode,算法大神左神(左程云)耗时100天打造算法与数据结构基础到
笔记内容
-
问题描述
- 比较器作用:重载比较运算符
- 比较器默认规则:返回负数第一个参数排前面;返回正数第二个参数拍前面
-
代码实现
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 + '}'; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」