java - 除了 Collections API 之外,在 Java 中覆盖 hashCode 有什么用?

标签 java hashmap hashcode hash-code-uniqueness

这个问题是面试官问的,大多数与哈希码相关的答案都用于分桶,它检查是否等于搜索对象。

是否有任何其他一般用例或场景,其中哈希码是有益的并且可以在例行程序中使用?

最近我使用了 JPA,它抛出异常 "Composite-id class does not override hashCode()" 但它再次被 hibernate 的实现类使用。狡猾的是,除了集合之外,我们还可以在哪些其他地方或场景中使用哈希码,尤其是您自己使用过哈希码的场景。

class a {
    public int hashCode() {
    }
}

class b {
    public static void main(String[] str) {
        //In what ways can i use hashcode here?
    }
}

最佳答案

假设您的类永远不会在任何集合中使用(尽管这种可能性很小),它将在多个地方和其他开发人员中使用。任何使用您的类的开发人员都会期望,如果该类的两个实例基于 equals 方法相等,则它们应该产生相同的 hashCode 值。如果不重写 hashCode 以与 equals 保持一致,那么这个基本假设将被打破,这将阻止他们的代码正常运行。

来自 Effective Java,第 3 版:

ITEM 11: ALWAYS OVERRIDE HASHCODE WHEN YOU OVERRIDE EQUALS

You must override hashCode in every class that overrides equals. If you fail to do so, your class will violate the general contract for hashCode, which will prevent it from functioning properly in collections such as HashMap and HashSet. Here is the contract, adapted from the Object specification :

• When the hashCode method is invoked on an object repeatedly during an execution of an application, it must consistently return the same value, provided no information used in equals comparisons is modified. This value need not remain consistent from one execution of an application to another.

• If two objects are equal according to the equals(Object) method, then calling hashCode on the two objects must produce the same integer result.

• If two objects are unequal according to the equals(Object) method, it is not required that calling hashCode on each of the objects must produce distinct results. However, the programmer should be aware that producing distinct results for unequal objects may improve the performance of hash tables.

The key provision that is violated when you fail to override hashCode is the second one: equal objects must have equal hash codes. Two distinct instances may be logically equal according to a class’s equals method, but to Object’s hashCode method, they’re just two objects with nothing much in common. Therefore, Object’s hashCode method returns two seemingly random numbers instead of two equal numbers as required by the contract.

关于java - 除了 Collections API 之外,在 Java 中覆盖 hashCode 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59464493/

相关文章:

java - 使用 javax.naming.NameNotFoundException 部署到 Weblogic

java - 如何使我的排序列表更加高效?

java - Neo4j 中的关系对计数

rust - 有没有办法为特定的 HashSet 或 HashMap 覆盖类型的相等性和哈希函数?

java - LinkedHashMap 是在双向链表的帮助下实现的,是否可以用两种方式迭代它?

java - 如何使用条目从 ListView 中获取特定键的值

algorithm - 我能否以保留字典字符串紧密度的方式将字符串编码为整数?

java - 比较和匹配不同大小的数组

java - 为什么哈希码不生成唯一的哈希码?

Java 字符串哈希码缓存