最近我读了这篇文章 开发人员工作文件。

该文档是关于有效和正确地定义hashCode()和equals(),但我无法弄清楚为什么我们需要覆盖这两个方法。

我如何决定有效地实现这些方法?


当前回答

考虑在一个桶中收集所有黑色的球。你的工作是像下面这样给这些球上色,并将其用于适当的游戏,

对于网球-黄色,红色。 板球-白色

现在水桶有三种颜色的球黄色,红色和白色。只有你知道哪个颜色适合哪个游戏。

给球上色-哈希。 选择比赛的球-平等。

如果你给球上色,然后有人选了板球或网球,他们不会介意颜色的!!

其他回答

当您希望将自定义对象作为Map中的键存储和检索时,您应该始终重写自定义对象中的equals和hashCode。 例如:

Person p1 = new Person("A",23);
Person p2 = new Person("A",23);
HashMap map = new HashMap();
map.put(p1,"value 1");
map.put(p2,"value 2");

这里p1和p2只被认为是一个对象,映射大小也只有1,因为它们相等。

考虑在一个桶中收集所有黑色的球。你的工作是像下面这样给这些球上色,并将其用于适当的游戏,

对于网球-黄色,红色。 板球-白色

现在水桶有三种颜色的球黄色,红色和白色。只有你知道哪个颜色适合哪个游戏。

给球上色-哈希。 选择比赛的球-平等。

如果你给球上色,然后有人选了板球或网球,他们不会介意颜色的!!

你必须重写hashCode()在每个 重写equals()的类。失败 这样做会导致违反 总合同 Object.hashCode(),它将防止 你的类不能正常运行 结合所有基于哈希的 集合,包括HashMap, HashSet和Hashtable。 摘自Joshua Bloch的《Effective Java》

通过一致地定义equals()和hashCode(),可以提高类作为基于散列的集合中的键的可用性。正如hashCode的API文档所解释的那样:“支持此方法是为了受益于诸如java.util.Hashtable所提供的哈希表。”

关于如何有效地实现这些方法的问题,最好的答案是建议你阅读《Effective Java》的第3章。

我正在研究解释“如果你只覆盖hashCode,那么当你调用myMap.put(first,someValue)时,它首先接受,计算它的hashCode并将其存储在给定的桶中。然后,当你调用myMap.put(first,someOtherValue)时,它应该根据Map文档将first替换为second,因为它们是相等的(根据我们的定义)。”:

我认为第二次添加myMap时应该是第二个对象比如myMap。put(second,someOtherValue)

它在使用值对象时很有用。以下摘自Portland Pattern Repository:

Examples of value objects are things like numbers, dates, monies and strings. Usually, they are small objects which are used quite widely. Their identity is based on their state rather than on their object identity. This way, you can have multiple copies of the same conceptual value object. So I can have multiple copies of an object that represents the date 16 Jan 1998. Any of these copies will be equal to each other. For a small object such as this, it is often easier to create new ones and move them around rather than rely on a single object to represent the date. A value object should always override .equals() in Java (or = in Smalltalk). (Remember to override .hashCode() as well.)