【问题标题】:How to search for an object in HashSet?如何在 HashSet 中搜索对象?
【发布时间】:2017-11-18 15:34:31
【问题描述】:

在我的 Java 程序中,GraphPoint 类使用两个坐标 mn 来描述组合结构的点,这两个坐标是它的唯一变量。我想创建一组无序的此类点:

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

现在我想知道collection 是否包含具有给定坐标的点。编写此代码的最快方法是什么?

【问题讨论】:

  • collection.contains(new GraphPoint(m, n))?
  • @Ryan 假设该类实现了equals()hashCode()

标签: java class contains hashset


【解决方案1】:

如果GraphPoint类正确实现hashCodeequals,则使用contains方法:

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

JavaDoc for the HashSet contains() method 将在返回 true 之前使用 equals 方法测试相等性。具体来说:

如果此集合包含指定元素,则返回 true。更正式地说,当且仅当此集合包含一个元素 e 满足 (o==null ? e==null : o.equals(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 对我之前回答的反馈

【讨论】:

  • xy 还是mn
  • 但是hashCode() 中有xy
  • 已修复 :) 再次感谢您的反馈!
猜你喜欢
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 2012-01-02
  • 2020-12-14
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
相关资源
最近更新 更多