Lux*_*ode 2 java collections hashset
我已经覆盖了Person类中的hashCode()和equals()方法,这样两个具有相同名称(一个String)的Person对象将被视为相等,但我的set仍然包含两个具有相同名称的Persons.
这是我的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();
}
Run Code Online (Sandbox Code Playgroud)
您的equals方法不会覆盖,因为它需要一个参数. Object.equals(object)Person
要避免此问题,请始终@Override在覆盖方法时添加注释.
这样,如果参数设置错误,您将收到错误消息.
| 归档时间: |
|
| 查看次数: |
589 次 |
| 最近记录: |