2017-06-16 68 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

修复:)再次感谢您的反馈! –