davesuen

哈希码和 equals() 都是用来比较的。

 

1. 哈希码的作用是用来提高比较的效率。因为当比较的对象比较复杂时,equals() 可能很耗时,但哈希码只需要比较一个 int 。哈希码常用于集 (set) 中的检索。

 

2. 规则:当我们 override 了 equals() 和 hashcode() 中的其中一个时,另一个也要重写。

因为 Java 的正确规则是,如果 equals() 为真,hashcode() 必须相同,但反之可以不成立。需要尽量遵循此此规则。

 

3. 一种合理的 hashcode() 的重写方式:

public int hashcode() {
    int hash = 1;
    hash = hash * 31 + aNonNullFieild.hashCode();
    hash = hash * 31 + (anotherField == null ? 0 : anotherField.hashCode());
    return hash;
}

分类:

技术点:

相关文章:

  • 2022-01-08
  • 2021-06-02
  • 2021-10-11
  • 2022-01-04
  • 2022-12-23
  • 2022-12-23
  • 2021-04-14
猜你喜欢
  • 2021-10-22
  • 2021-12-16
  • 2022-02-15
  • 2021-12-09
  • 2021-12-08
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案