hashcode和equals关系详解

hashcode和equals关系详解

equals方法

默认实现是比较对象引用,子类通常需要重写。

1
2
3
4
5
6
7
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
User user = (User) obj;
return Objects.equals(id, user.id) && Objects.equals(name, user.name);
}

hashCode方法

返回对象的哈希码,用于哈希表(如HashMap)快速查找。

1
2
3
4
@Override
public int hashCode() {
return Objects.hash(id, name);
}

关系规则

  • 一致性:equals比较为true时,hashCode必须相同
  • 效率:hashCode相同,equals不一定为true

在集合中的使用

1
2
3
// HashMap先比较hashCode,再比较equals
Map<User, String> map = new HashMap<>();
map.put(new User(1, "Tom"), "value");

总结

重写equals必须重写hashCode,以保证在集合中的正确性。