【发布时间】: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