当我为我的元素创建一个哈希集,出于某种原因,我可以添加重复的元素。我确实重写了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
我们清楚地看到它们具有相同的哈希码,那么为什么他们都在HashSet的?我认为哈希集的实用程序是在它不能包含重复的事实?我错过了什么吗?这里是equals和hashCode:
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;
}
你可以发布'Point2D.Double'的equals方法吗?你可能会遇到这样的问题 - 在Point2D.hashCode中你手工为'Point2D.Double'生成'hashCode',但在'Point2D.equals'中依赖'Point2D.Double.equals' - 这可能是错误的。 –
尝试在您的equals方法中添加“@ Override”。总是。 – Pshemo
@BoristheSpider我怀疑OP正在使用'java.awt.geom.Point2D.Double'。 – Pshemo