gpt4 book ai didi

java - 为什么我的哈希集包含重复项?

转载 作者:行者123 更新时间:2023-11-30 10:31:32 26 4
gpt4 key购买 nike

<分区>

当我为我的元素创建哈希集时,出于某种原因我可以向其中添加重复元素。我确实覆盖了 equals 和 hashcode 方法。下面是我的一些代码和我的问题的一个例子。为简单起见,我将我的元素命名为“元素”。

set.add(new element(new Point2D.Double(0,1), new Point2D.Double(2, 3), true));
set.add(new element(new Point2D.Double(0,1), new Point2D.Double(2, 3), true));
for (element e : set)
System.out.println("set element : " + e.firstPoint2D.toString()
+ e.secondPoint2D.toString()
+ e.lastBoolean
+ " and hashcode = " + e.hashCode());

返回:

set element : Point2D.Double[0.0, 1.0] Point2D.Double[2.0, 3.0] true 
and hashcode = 3211
set element : Point2D.Double[0.0, 1.0] Point2D.Double[2.0, 3.0] true
and hashcode = 3211

我们清楚地看到它们具有相同的哈希码,那么为什么它们都在哈希集中?我认为哈希集的实用性在于它不能包含重复项?我错过了什么吗?这是等于和哈希码:

public boolean equals(element e) {
if (this.firstPoint2D.equals(e.firstPoint2D) &&
this.secondPoint2D.equals(e.secondPoint2D) &&
this.lastBoolean == e.lastBoolean)
return true;
else
return false;
}

@Override
public int hashCode() {
int result = (int)(firstPoint2D.getX() + 10*firstPoint2D.getY()
+ 100*secondPoint2D.getX() + 1000*secondPoint2D.getY());
if (lastBoolean)
return result + 1;
else
return result;
}

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