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集合可以正常工作

相关推荐
武子康8 小时前
Java-109 深入浅出 MySQL MHA主从故障切换机制详解 高可用终极方案
java·数据库·后端·mysql·性能优化·架构·系统架构
秋难降8 小时前
代码界的 “建筑师”:建造者模式,让复杂对象构建井然有序
java·后端·设计模式
孤雪心殇8 小时前
如何安全,高效,优雅的提升linux的glibc版本
linux·后端·golang·glibc
BillKu9 小时前
Spring Boot 多环境配置
java·spring boot·后端
new_daimond9 小时前
Spring Boot项目集成日志系统使用完整指南
spring boot·后端
哈基米喜欢哈哈哈10 小时前
Kafka复制机制
笔记·分布式·后端·kafka
君不见,青丝成雪10 小时前
SpringBoot项目占用内存优化
java·spring boot·后端
追逐时光者11 小时前
一个 .NET 开源、功能强大的在线文档编辑器,类似于 Microsoft Word,支持信创!
后端·.net
想买CT5的小曹11 小时前
SpringBoot如何获取系统Controller名称和方法名称
java·spring boot·后端