是否有任何理由从 hashCode 方法返回常量值?

Is there any reason for returning constant value from hashCode method?

我有一个问题与 java.lang.Object 中关于 hashCode 方法的广泛讨论主题相关。只是有什么理由让我在某些用例中 return 来自 hashCode()?

的常量值
public int hashCode()
{
   return 3;
}

如果您发现一些文章或 SO 线程直接回答了我的问题,我将不胜感激。坦白说我做不到。

我的想法:

来自 docs.oracle.com object hashCode()(我知道在 SO 中被多次引用):

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables."

所以理论上hashCode()可以return一个常数值。在我的想象和我所读到的内容中,所有对象在使用例如 HashMap 时将被放置在同一个桶中。举个例子,假设 1000 个元素将被放置在完全相同的哈希桶中(换句话说,将有 1000 次冲突)并且在必须迭代 1000 个元素的错误情况下找到特定的一个。然后它将执行类似于 LinkedList 集合(如果我错了请纠正我)。

基于上述,hashCode() 可以 return 一个常量值,但它会破坏使用 hash... 集合获得的性能。那么在某些特定示例中这样做有什么意义吗?

编辑: 我发现了一个具有常量 hashCode 方法的特定示例 基于 Vlad 的 Mihalcea 文章:How to implement equals and hashCode using JPA entity identifier,(Hibernate)。 HashCode 在实体状态转换之间不同,因此它应该 return 常量值。引用文章:

When the entity was first stored in the Set, the identifier was null. After the entity was persisted, the identifier was assigned to a value that was automatically generated, hence the hashCode differs. For this reason, the entity cannot be found in the Set after it got persisted.

所以有一个实际的例子,但正如它指出的那样以性能为代价。如果除了实体 ID 之外还有一个业务唯一非空标识符,最好使用它以利用在多个 Hash... 存储桶中存储实体。

通常,在覆盖哈希码时,您永远不会return静态成员。我以前从未这样做过,但我什至可以想象的唯一可能的用例是单例,在这种情况下,您期望运行时只有 1 个未延迟初始化的实例。这有点没用,因为如果你将 class 设计为使用单例模式,你就永远不需要使用 equals/hashcode.

当您知道 class 将只有很少的唯一实例时,常量 hashCode 才有意义,理想情况下只有 1 个。

例如在实施 algebraic data types, or the Singleton 设计模式时会出现这种情况。

在代数数据类型中,无参数数据类型的所有实例都彼此相等。因此 hashCode 必须 return 所有实例的相同值。

在单例模式中,class 将只有一个实例。因此hashCodereturns的值是什么并不重要,它可以return一个常量。