Java - TreeSet和hashCode() [英] Java - TreeSet and hashCode()

查看:158
本文介绍了Java - TreeSet和hashCode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 <$ c $的快速提问c> TreeSet 集合和 hashCode 方法。我有一个 TreeSet 我正在添加对象,在添加对象之前,我检查它是否存在于 TreeSet中使用 包含 方法。

I have a quick question about TreeSet collections and hashCode methods. I have a TreeSet and I'm adding objects to it, before I add an object, I check to see if it exists in the TreeSet using the contains method.

我有2个不同的对象,每个对象产生一个独特的hashCode使用我的hashCode方法实现,例如如下:

I have 2 distinct objects, each of which produce a distinct hashCode using my implementation of the hashCode method, example below:

public int hashCode()
{
    int hash = 7;
    hash = hash * 31 + anAttribute.hashCode();
    hash = hash * 31 + anotherAttribute.hashCode();
    hash = hash * 31 + yetAnotherAttribute.hashCode();
    return hash;
}

特定运行的hashCodes是:76126352和76126353(对象只有不同一个属性中的一个数字)。

The hashCodes for a particular run are: 76126352 and 76126353 (the objects only differ by one digit in one attribute).

即使hashCodes不同,contains方法也会为这些对象返回true。有什么想法吗?这真的令人困惑,真的很感激帮助。

The contains method is returning true for these objects, even though the hashCodes are different. Any ideas why? This is really confusing and help would really be appreciated.

推荐答案

TreeSet不使用 hashCode 。它使用 compareTo 或传递给构造函数的Comparator。这是由像contains这样的方法用来查找集合中的对象。

TreeSet does not use hashCode at all. It uses either compareTo or the Comparator you passed to the constructor. This is used by methods like contains to find objects in the set.

所以问题的答案是你的compareTo方法或比较器被定义为两个对象有问题被认为是平等的。

So the answer to your question is that your compareTo method or your Comparator are defined so that the two objects in question are considered equal.

来自javadocs:

From the javadocs:


一个TreeSet实例使用
compareTo(或compare)方法执行所有
元素比较,因此从
的角度来看,这个
方法认为相等的两个
元素set,equal。

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆