HashSet包含重复的条目 [英] HashSet contains duplicate entries
问题描述
当equals方法表明它们是相同的时,HashSet只存储值1。这就是我的想法。
A HashSet only stores values ones, when the equals method says that they're the same. Thats what I thought.
但是现在我将元素添加到HashSet中,其中equals方法返回true并且集合的大小仍在增长?抱歉,我很困惑。我错了一些提示会很好。
But now i'm adding Elements to a HashSet where the equals method returns true and the size of the set still grows?? sorry I'm confused. Some hints where i'm wrong would be nice.
Element t1 = new Element(false, false, false, false);
Element t2 = new Element(true, true, true, true);
Element t3 = new Element(false, false, false, false);
if (t1.equals(t3))
System.out.println("they're equal");
Set<Element> set = new HashSet<>();
set.add(t1);
set.add(t2);
set.add(t3);
System.out.println("set size: " + set.size());
所以在这个例子中我的控制台输出是:
so in this example my console output is:
他们是平等的
设置尺寸:3
they're equal
set size: 3
这使得对我没有意义..大小不应该是2?
That makes no sense to me.. shouldn the size be 2?
推荐答案
问题是你的元素
class没有覆盖等于
和 hashCode
方法或这些实现被破坏。
The problem is that your Element
class has not overridden the equals
and hashCode
methods or these implementations are broken.
来自 对象#equals
方法javadoc:
From Object#equals
method javadoc:
equals方法在非null对象引用上实现等价关系:
The equals method implements an equivalence relation on non-null object references:
- 它是自反的:对于任何非空引用值x,x .equals(x)应该返回true。
- 它是对称的:对于任何非空引用值x和y,当且仅当y时,x.equals(y)应该返回true。 EQUA ls(x)返回true。
- 对于任何非空引用值x,y和z,如果x.equals(y)返回true和y.equals( z)返回true,然后x.equals(z)应该返回true。
它是一致的:对于任何非空引用值x和y,-x.equals(y)的多次调用始终返回true或始终返回false,前提是没有修改对象的equals比较中使用的信息。 - 对于任何非空引用值x,x.equals(null)应返回false。
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of -x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
- For any non-null reference value x, x.equals(null) should return false.
来自 Object#hashCode
method javadoc:
From Object#hashCode
method javadoc:
hashCode的一般合约是:
The general contract of hashCode is:
- 每当在执行Java应用程序期间多次在同一对象上调用它时,hashCode方法必须始终返回如果修改了对象的等比较中使用的信息,则不会使用相同的整数。从应用程序的一次执行到同一应用程序的另一次执行,此整数不需要保持一致。
- 如果两个对象根据equals(Object)方法相等,则调用hashCode方法两个对象中的每一个都必须产生相同的整数结果。
- 如果两个对象根据equals(java.lang.Object)方法不相等,则不需要调用两个对象中的每一个上的hashCode方法必须产生不同的整数结果。但是,程序员应该知道为不等对象生成不同的整数结果可能会提高哈希表的性能。
确保这些方法的实现满足这些规则并且设置
(由 HashSet
支持)将按预期工作。
Make sure the implementations of these methods satisfy these rules and your Set
(backed by a HashSet
) will work as expected.
这篇关于HashSet包含重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!