0

我在弄清楚如何为以下示例实现有效的哈希码时遇到了一些麻烦:

我有 2 节课:

Class A
{
} 

Class B 
{
  protected List<A> constitutingObjects;
}

已经覆盖了 equal,所以如果 A 是 B.构成对象的一部分,则对象 A 等于对象 B。我遇到的问题是我不确定如何为此实现哈希码。

有任何想法吗 ?

谢谢。

4

2 回答 2

1

TL; DR:您尝试做的事情没有意义。退后一步,尝试以不同的方式处理更大的任务。

已经被覆盖 equal 所以如果 A 是 B.构成对象的一部分,则 A 类等于 B 类

这听起来是个非常糟糕的主意。很难说这些对象代表什么,但包含集合的东西在逻辑上不等于该集合的元素——购物清单不等于“牛奶”。

不要忘记您必须遵循java.lang.Object文档中指定的要求。许多其他代码将取决于这些保证。

Implementing hashCode will basically be impossible unless you just return a constant. The hash code of two equal objects has to be equal, which means the hash code of any instance of ClassB would have to be equal to the hash code of every element of constitutingObjects, which means that all of those elements would have to have the same hash code. Unless instances of ClassA somehow "knew" what their container was, I don't see how this could be possible.

于 2012-08-22T16:26:05.240 回答
0

在 Java 中定义equals和定义hashCode时,您不是在测试 2 个类是否相等,您实际上是在根据equals方法测试相同类型(类)的 2 个对象是否相等,或者它们可以在同一个“桶”中(逻辑上对象组)根据hashCode.

因此,如果 x 和 y 是 A 类型的 2 个对象:

A x = new A();
A y = new A();
  • 如果x.equals(b)为真则x.hashCode()必须等于y.hashCode()
  • 如果x.hashCode() == y.hashCode()thenx.equals(y)可以是真或假
于 2012-08-22T16:24:20.630 回答