2017-04-01 46 views
1

當我爲我的元素創建一個哈希集,出於某種原因,我可以添加重複的元素。我確實重寫了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; 
} 
+1

你可以發佈'Point2D.Double'的equals方法嗎?你可能會遇到這樣的問題 - 在Point2D.hashCode中你手工爲'Point2D.Double'生成'hashCode',但在'Point2D.equals'中依賴'Point2D.Double.equals' - 這可能是錯誤的。 –

+2

嘗試在您的equals方法中添加「@ Override」。總是。 – Pshemo

+0

@BoristheSpider我懷疑OP正在使用'java.awt.geom.Point2D.Double'。 – Pshemo

回答

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

Here的的javadoc equals()

+0

現在沒有更多的重複!謝謝 –