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

相关推荐
掘金者阿豪12 小时前
UUID的隐形成本:一个让数据库“慢下来”的陷阱
后端
用户0844652563712 小时前
Docker 部署 MongoDB Atlas 到服务端
后端
Anita_Sun13 小时前
一看就懂的 Haskell 教程 - 类型推断机制
后端·haskell
Anita_Sun13 小时前
一看就懂的 Haskell 教程 - 类型签名
后端·haskell
七八星天13 小时前
C#代码设计与设计模式
后端
砍材农夫14 小时前
threadlocal
后端
神奇小汤圆14 小时前
告别手写HTTP请求!Spring Feign 调用原理深度拆解:从源码到实战,一篇搞懂
后端
布列瑟农的星空14 小时前
前端都能看懂的Rust入门教程(三)——控制流语句
前端·后端·rust
汤姆yu14 小时前
基于springboot的尿毒症健康管理系统
java·spring boot·后端
暮色妖娆丶14 小时前
Spring 源码分析 单例 Bean 的创建过程
spring boot·后端·spring