gpt4 book ai didi

java - HashSet 包含重复条目

转载 作者:搜寻专家 更新时间:2023-10-30 19:52:21 25 4
gpt4 key购买 nike

当 equals 方法表明它们相同时,HashSet 仅存储值 ones。我就是这么想的。

但现在我将元素添加到 HashSet,其中 equals 方法返回 true 并且集合的大小仍在增长?对不起,我很困惑。在我错的地方给出一些提示会很好。

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());

所以在这个例子中我的控制台输出是:

they're equal
set size: 3

这对我来说毫无意义.. 大小应该是 2 吗?

最佳答案

问题是您的 Element 类没有覆盖 equalshashCode 方法,或者这些实现已损坏。

来自 Object#equals方法 javadoc:

The equals method implements an equivalence relation on non-null object references:

  • 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方法 javadoc:

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

确保这些方法的实现满足这些规则,并且您的 Set(由 HashSet 支持)将按预期工作。

关于java - HashSet 包含重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com