我的 HashSet 包含(有意义的等效)重复项!

发布于 2024-11-05 09:35:58 字数 647 浏览 1 评论 0原文

我已经重写了 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();
}

I've overridden the hashCode() and equals() methods in my Person class so that two Person objects with the same name (a String) will be viewed as equal, but my set still contains two Persons with the same name.

Here's the code from my Person class:

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();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幸福丶如此 2024-11-12 09:35:58

您的 equals 方法不会覆盖 Object.equals(object),因为它采用 Person 作为参数。

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

Your equals method isn't overriding Object.equals(object), since it takes a Person as a parameter.

To avoid this issue, always add the @Override annotation when you override a method.
This way, you'll get an error if you get the parameters wrong.

离笑几人歌 2024-11-12 09:35:58

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

RC

Did the duplicate person object get added when it was equivalent, or did the person object get added when it was not a duplicate, and then modified so that it was a duplicate? The latter case is not defined for java.util.Set.

rc

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文