我有一个关于
我有两个不同的对象,每个对象都使用我的实现的hashCode方法产生一个不同的hashCode,例如下面的例子:
TreeSet
集合和hashCode
方法的问题。我有一个TreeSet
,我正在向其中添加对象,在添加对象之前,我使用contains
方法检查它是否存在于TreeSet
中。我有两个不同的对象,每个对象都使用我的实现的hashCode方法产生一个不同的hashCode,例如下面的例子:
public int hashCode()
{
int hash = 7;
hash = hash * 31 + anAttribute.hashCode();
hash = hash * 31 + anotherAttribute.hashCode();
hash = hash * 31 + yetAnotherAttribute.hashCode();
return hash;
}
一个特定运行的哈希码为:76126352和76126353(这些对象只在一个属性中的一位数字上有所不同)。
即使哈希码不同,contains方法仍然返回这些对象的真值。有任何想法为什么会这样吗?这真的很困惑,需要帮助。