Java 为什么我的哈希集包含重复项?
当我为元素创建哈希集时,出于某种原因,我可以向其中添加重复的元素。我确实重写了equals和hashcode方法。下面是我的代码和我的问题的一个例子。为了简单起见,我将我的元素命名为“元素” 这将返回:Java 为什么我的哈希集包含重复项?,java,hashset,Java,Hashset,当我为元素创建哈希集时,出于某种原因,我可以向其中添加重复的元素。我确实重写了equals和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,
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
我们清楚地看到它们有相同的hashcode,那么为什么它们都在hashset中呢?我认为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;
}
您的
equals
方法未被正确重写,因此,它使用Object
类的eqauls()
方法,而不是被重写的版本equals()
方法ob对象
类接受一个对象
参数,而您覆盖的对象接受元素
,以下应该可以工作:
@Override
public boolean equals(Object e) {
if ( e instanceof element &&
this.firstPoint2D.equals(((element)e).firstPoint2D) &&
this.secondPoint2D.equals(((element)e).secondPoint2D) &&
this.lastBoolean == ((element)e).lastBoolean)
return true;
else
return false;
}
的javadoc for
equals()
您能否发布Point2D.Double
的equals
方法?问题可能就在这里-在Point2D.hashCode
中,您手动为Point2D.Double
生成hashCode
,但在Point2D.equals中,您依赖Point2D.Double.equals
-这可能是错误的。请尝试将@Override
添加到equals方法中。始终如此。@BoristheSpider我怀疑OP使用的是java.awt.geom.Point2D.Double
@Pshemo刚刚看到你的评论,这肯定是问题所在。我甚至没有注意到。。。哎呀。无论哪种方式,混合外部和内部等于
和hashCode
都很奇怪。现在不再重复了!谢谢
@Override
public boolean equals(Object e) {
if ( e instanceof element &&
this.firstPoint2D.equals(((element)e).firstPoint2D) &&
this.secondPoint2D.equals(((element)e).secondPoint2D) &&
this.lastBoolean == ((element)e).lastBoolean)
return true;
else
return false;
}