java - 面试难题 - 为什么我们应该重写 hashCode 和 equals 方法

标签 java memory-management hashmap equals hashcode

我参加了一次面试,面试官问了一个问题

面试官 -如果我们打算使用类的对象作为 HashMap 键,为什么我们应该重写类的 hashCode 和 equals 方法。

我 -我已经告诉他完整的流程。 HashMap内部如何使用hashcode和equals方法(Bucket逻辑)。

但他对我的回答不满意。他告诉我这只是基本用途,你已经完美地解释了它,但我想知道它的高级重要性而不是基本(他也给了我一些线索 - 它有助于内存管理)。

我在网上搜索过,但没有得到答案。

还有其他重要性吗?如果是,那是什么?

链接/文档将受到高度赞赏。

提前致谢......

最佳答案

这可能有帮助吗? (摘自http://apmblog.compuware.com/2011/12/15/the-top-java-memory-problems-part-2/)

Incorrect implementation of equal and hashcode

The relationship between the hashcode method and memory problems is not obvious at first glance. However, if we consider where the hashcode method is of high importance this becomes clearer.

The hashcode and equals methods are used within hash maps to insert and find objects based on their key. However, if the implementation of the operator is faulty, existing entries are not found and new ones keep being added.

While the collection responsible for the memory problem can be identified very quickly, it may be difficult to determine why the problem occurs.

关于java - 面试难题 - 为什么我们应该重写 hashCode 和 equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25761992/

相关文章:

java - 如果给定时间段内没有传入事件,如何触发 esper

c - 如何为 typedef 结构正确分配内存

c - 为什么我的这段代码的 malloc 版本会失败?

java - 如何分别从 HashMap 获取对象?

java - 如果我在其中放入字符,HashMap 中的 containsKey 方法会检查整数吗?

c++ - gcc std::unordered_map 实现速度慢吗?如果是这样 - 为什么?

java - 从 Netbeans 环境运行 正确打印文本。直接运行同一个JAR不会

java - 用于存储照片的 Blobstore 或云存储

java - 从 Java 中的给定树中检索所有节点

c++ - 如何耗尽内存?