【问题标题】:my HashSet contains (meaningfully equivalent) duplicates!我的 HashSet 包含(有意义的等效)重复项!
【发布时间】:2011-05-08 03:35:20
【问题描述】:

我在我的 Person 类中重写了 hashCode() 和 equals() 方法,这样两个同名的 Person 对象(一个字符串)将被视为相等,但我的集合仍然包含两个同名的 Person .

这是我的 Person 类的代码:

public boolean equals(Person aPerson) {
    Person p = (Person) aPerson;
    //Since name is a String, we can just use
    //the overridden equals() method to ask
    //one name if it's equal to the other
    //person's name.
    return getName().equals(p.getName());
}

public int hashCode() {
    //Strings also have an overridden hashCode() method
    //so we can just return the result of calling hashCode()
    //on the name (instead of the object!)
    return name.hashCode();
}

【问题讨论】:

    标签: java collections hashset


    【解决方案1】:

    您的equals 方法没有覆盖Object.equals(<b>object</b>),因为它采用Person 作为参数。

    为避免此问题,请始终在重写方法时添加 @Override 注释。
    这样,如果参数错误,就会报错。

    【讨论】:

    • 哦,对了,哈哈!它应该是 public boolean equals(Object aPerson)!
    • 您的 IDE 应该突出显示您的演员阵容是多余的。 ;)
    【解决方案2】:

    重复的人对象是在等价时被添加的,还是在人对象不是重复的时候被添加,然后修改为重复?后一种情况没有为 java.util.Set 定义。

    rc

    【讨论】:

      猜你喜欢
      • 2018-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      相关资源
      最近更新 更多