我有一个关于 TreeSet
的快速问题 Collection 和hashCode
方法。我有一个 TreeSet
并向其添加对象,在添加对象之前,我使用 contains
检查它是否存在于 TreeSet
中方法。
我有 2 个不同的对象,每个对象都使用我对 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;
}
特定运行的 hashCode 为:76126352 和 76126353(对象在一个属性中仅相差一位数)。
contains 方法为这些对象返回 true,即使 hashCode 不同。任何想法为什么?这真的很令人困惑,我们将不胜感激。
最佳答案
TreeSet 根本不使用hashCode
。它使用 compareTo
或您传递给构造函数的 Comparator。 contains 等方法使用它来查找集合中的对象。
所以你的问题的答案是你的 compareTo 方法或你的 Comparator 被定义为使得所讨论的两个对象被认为是相等的。
来自 javadocs:
a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.
关于Java - TreeSet 和 hashCode(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29936583/