【问题标题】:Why does my hashset contain duplicates? [duplicate]为什么我的哈希集包含重复项? [复制]
【发布时间】:2017-04-01 09:21:03
【问题描述】:

当我为我的元素创建一个哈希集时,出于某种原因,我可以向其中添加重复的元素。我确实覆盖了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

我们清楚地看到它们具有相同的哈希码,那么为什么它们都在哈希集中?我认为哈希集的实用性在于它不能包含重复项?我错过了什么吗?这是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.Doubleequals 方法吗?您的问题可能存在 - 在Point2D.hashCode 中,您手动为Point2D.Double 生成hashCode,但在Point2D.equals 中您依赖Point2D.Double.equals - 这可能是错误的。
  • 尝试将 @Override 添加到您的 equals 方法中。总是。
  • @BoristheSpider 我怀疑 OP 正在使用java.awt.geom.Point2D.Double
  • @Pshemo 刚刚看到您的评论,这肯定是问题所在。我什至没有注意到...哎呀。无论哪种方式,混合外部和内部 equalshashCode 都是奇怪的。

标签: java hashset


【解决方案1】:

您的 equals 方法未被正确覆盖,因此,它使用 Object 类的 eqauls() 方法而不是被覆盖的版本。 equals() 方法 ob Object 类接受 Object 参数,而您覆盖的方法接受 element,以下应该可以工作:

@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;
}

Hereequals() 的 javadoc。

【讨论】:

  • 现在不再重复!谢谢
猜你喜欢
  • 2011-12-20
  • 2011-01-12
  • 2014-11-12
  • 2018-04-07
  • 2022-01-21
  • 1970-01-01
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多