java优先队列,equals方法

优先队列的申明:

 Queue<Student> queue = new PriorityQueue<>();

要使得优先队列的排序起作用,就要让这个student实现Comparable中的compareTo方法

复制代码
 @Override
    public int compareTo(Object o) {
        Student another = (Student) o;
        Integer anotherAge = another.age;
        if (this.age < anotherAge) {
            return -1;
        } else if (this.age == anotherAge) {
            return 0;
        }
        return 1;
    }
复制代码

我在这里是按年龄排序,年龄小的返回-1,也就是正常情况下,这样优先队列里每次取出的就是年龄最小的那个student

 

此外关于重写equals问题

例如

@Override
    public boolean equals(Object obj) {
        Student another = (Student) obj;
        if (another.name.equals(this.name)) {
            return true;
        }
        return false;
    }
  Student student1 = new Student("1", 20, "徐康");
  Student student2 = new Student("2", 21, "徐康");

调用student1.equals(student2)返回true

Stack<Student> students=new Stack<>();
students.add(student1);
System.out.println(students.contains(student2));

List<Student> list=new ArrayList<>();
list.add(student1);
System.out.println(list.contains(student2));

两个都输出true

posted @   梦醒如赦  阅读(49)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示