hashCode和equals

equals是用于比较两个对象是否相同

  • 对象1.equals(对象2)
  • 每个对象的equals可以重写,自定义比较规则
kotlin 复制代码
@Data
public class Student {

  private Integer id;

  private String name;

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Student student = (Student) o;
    return Objects.equals(id, student.id) && Objects.equals(name, student.name);
  }

}

student对象就是重写了比较规则,如果两个student id相同、name相同,就认为是同一个学生,如果不重写的话,student对象的equals方法就会调用Object的equals方法

hashCode方法

为什么要重写hashcode方法? 拿上面的例子来说,期望将学生放入HashSet,如果不重写hashSet,会导致即使认为是equals的两个对象被放入set两次,因为放入hashSet前会对对象做hash运算,两个对象如果不重写hashCode就会使用Object的hashCode,计算大概是通过对象地址然后加工处理得出,所以两个对象被认为hash值不同,认为是两个不同的对象

java 复制代码
Student student1 = new Student(1,"张三");
Student student2 = new Student(1,"张三");
student1.equals(student2); //返回true,因为重写了equals方法
HashSet<Student> hashSet = new HashSet<>();
hashSet.put(student1);
hashSet.put(student2);
hashSet.size() // 返回2,因为没有重写hashCode,被认为是不同对象多次放入

需要将student的hashCode进行手动重写
@Override
public int hashCode() {
    return Objects.hash(id, name); // 与 equals() 逻辑一致
}

总结

如果不使用hash相关的工具类集合,equals和hashCode是没有直接关联的,只不过Object的默认equals方法是使用的hashCode方法。 equals和hashCode都按相同规则重写,才会让hash集合可以正常工作

相关推荐
ai小鬼头18 分钟前
AIStarter教你快速打包GPT-SoVITS-v2,解锁AI应用市场新玩法
前端·后端·github
paopaokaka_luck1 小时前
基于SpringBoot+Vue的汽车租赁系统(协同过滤算法、腾讯地图API、支付宝沙盒支付、WebsSocket实时聊天、ECharts图形化分析)
vue.js·spring boot·后端·websocket·算法·汽车·echarts
giao源1 小时前
Spring Boot 整合 Shiro 实现单用户与多用户认证授权指南
java·spring boot·后端·安全性测试
【本人】1 小时前
Django基础(四)———模板常用过滤器
后端·python·django
豌豆花下猫2 小时前
Python 潮流周刊#111:Django迎来 20 周年、OpenAI 前员工分享工作体验(摘要)
后端·python·ai
LaoZhangAI2 小时前
ComfyUI集成GPT-Image-1完全指南:8步实现AI图像创作革命【2025最新】
前端·后端
LaoZhangAI2 小时前
Cline + Gemini API 完整配置与使用指南【2025最新】
前端·后端
LaoZhangAI3 小时前
Cline + Claude API 完全指南:2025年智能编程最佳实践
前端·后端