hashCode和equals

60 阅读1分钟

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

  • 对象1.equals(对象2)
  • 每个对象的equals可以重写,自定义比较规则
@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值不同,认为是两个不同的对象

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