在我的Java程序中,类GraphPoint
描述了使用两个坐标m和n的组合结构的点,它们是它的唯一变量。我想创建一个无序的这样的点:如何在HashSet中搜索对象?
Set<GraphPoint> collection = new HashSet<>();
现在我想知道是否collection
包含具有给定坐标的点。对此进行编码的最快方法是什么?
在我的Java程序中,类GraphPoint
描述了使用两个坐标m和n的组合结构的点,它们是它的唯一变量。我想创建一个无序的这样的点:如何在HashSet中搜索对象?
Set<GraphPoint> collection = new HashSet<>();
现在我想知道是否collection
包含具有给定坐标的点。对此进行编码的最快方法是什么?
如果GraphPoint
类实现hashCode
和equals
正确,然后使用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
,可以实现hashCode
和equals
如下:
@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对我以前回答的反馈
'collection.contains(new GraphPoint(m,n))'? – Ryan
@Ryan假设类实现了'equals()'和'hashCode()'。 – shmosel