当 equals 方法说它们相同时,HashSet 只存储值.我就是这么想的.
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?
问题是你的 Element
类没有覆盖 equals
和 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 方法在非空对象引用上实现等价关系:
The equals method implements an equivalence relation on non-null object references:
来自 Object#hashCode代码> 方法javadoc:
From Object#hashCode
method javadoc:
hashCode的一般合约是:
The general contract of hashCode is:
确保这些方法的实现满足这些规则,并且您的 Set
(由 HashSet
支持)将按预期工作.
Make sure the implementations of these methods satisfy these rules and your Set
(backed by a HashSet
) will work as expected.
这篇关于HashSet 包含重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!