2017-06-16 62 views
-1

在我的Java程序中,類GraphPoint描述了使用兩個座標mn的組合結構的點,它們是它的唯一變量。我想創建一個無序的這樣的點:如何在HashSet中搜索對象?

Set<GraphPoint> collection = new HashSet<>(); 

現在我想知道是否collection包含具有給定座標的點。對此進行編碼的最快方法是什麼?

+3

'collection.contains(new GraphPoint(m,n))'? – Ryan

+4

@Ryan假設類實現了'equals()'和'hashCode()'。 – shmosel

回答

2

如果GraphPoint類實現hashCodeequals正確,然後使用contains方法:

collection.contains(new GraphPoint(m,n)) 

JavaDoc for the HashSet contains() method將使用equals方法返回true之前測試平等。具體而言:

如果此集合包含指定的元素,則返回true。更正式地說,當且僅當這個集合包含一個使得(o == null?e == null:o.equals(e))的元素e時才返回true。

爲了完整起見,假設你GraphPoint該類行爲完全像一個Point,可以實現hashCodeequals如下:

@Override 
public int hashCode() { 
    int result = m; 
    result = 31 * result + n; 
    return result; 
} 

@Override 
public boolean equals(Object other){ 
    if (this == other) return true; 
    if (!(other instanceof GraphPoint)) return false; 
    final GraphPoint that = (GraphPoint) other; 
    return this.m == that.m && this.n == that.n; 
} 

推薦閱讀:Effective Java: Equals and HashCode

還,感謝@Federico_Peralta_Schaffner和@shmosel對我以前回答的反饋

+0

是'x'和'y'還是'm'和'n'? – shmosel

+0

但你在'hashCode()'中有'x'和'y'。 – shmosel

+0

修復:)再次感謝您的反饋! –