编写完美的equals方法的建议:
public class Test {
String field1 = null;
String field2 = null;
public Test() {
}
@Override
// 显式参数命名为otherObject,稍后需要将它转换成另一个叫做other变量
public boolean equals(Object otherObject) {
// 检测this与otherObject是否引用同一个对象
if (this == otherObject) {
return true;
}
// 检测otherObject是否属于为null,如果为null,返回false
if (otherObject == null) {
return false;
}
// 比较this与otherObject是否是同一类型,如果equals在每个子类中有所改变就是用getClass()检查
if (this.getClass() != otherObject.getClass()) {
return false;
}
// 如果所有的子类拥有统一的equals语义,就是用instanceof检查
if (!(otherObject instanceof Test)) {
return false;
}
// 将otherObject转换为相应的类类型变量
Test other = (Test) otherObject;
// 现在开始对所有需要比较的域进行比较了。使用==比较基本类型域,使用equals比较对象域。
return field1 == other.field1 && field2.equals(field2);
}
}
如果重新定义equals就必须重新定义hashCode方法,以便用户可以将对象插入到hash表中。equals如果返回需与hashCode一致。