我参加了一次面试,面试官问了一个问题
面试官 -如果我们打算使用类的对象作为 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/