-- Start
equals 和 hashCode 的定义必须一致, 如果 x.equals(y) == true, 那么 x.hashCode 与 y.hashCode 必须返回相同的值, 所以如果重写了 equals 方法, 那么我们必须重写 hashCode 方法.
class Poeple {
private String name;
private int age;
@Override
public boolean equals(Object otherObject) {
if (this == otherObject)
return true;
if (otherObject == null)
return false;
if (getClass() != otherObject.getClass()) // 注意此处, 我们不能通过 instanceof 来判断
return false;
Poeple other = (Poeple) otherObject;
return name.equals(other.name) // 使用 equals 对象域
&& age == other.age; // 使用 == 比较基本类型
}
@Override
public int hashCode() {
return 17 * name.hashCode() + 31 * age; // 计算所有用于equals方法的域
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class Student extends Poeple {
private int grade;
@Override
public boolean equals(Object otherObject) {
if (!super.equals(otherObject)) // 此处需要调用父类的 equals 方法
return false;
Student other = (Student) otherObject;
return grade == other.grade;
}
@Override
public int hashCode() {
return super.hashCode() + 37 * grade; // 此处需要调用父类的 hashCode 方法
}
}
虽然实现 HashCode 方法比较简单, 不过 Apache Commons 包中提供了 HashCodeBuilder 类, 它可以帮助我们实现 HashCode 方法.
--更多参见:Java 精萃
-- 声 明:转载请注明出处
-- Last Updated on 2012-05-18
-- Written by ShangBo on 2012-05-18
-- End