我的 HashSet 包含(有意义的等效)重复项!
我已经重写了 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
equals
方法不会覆盖Object.equals(object)
,因为它采用Person
作为参数。为了避免此问题,请在重写方法时始终添加
@Override
注释。这样,如果参数错误,就会出现错误。
Your
equals
method isn't overridingObject.equals(object)
, since it takes aPerson
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.
重复的 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