很多时候看到许多地方说在自己的类里重写equals()方便用以比较两个对象相等,但一直未能详细探索到底怎么重写是比较好的方式。如今看到书上的一个模板,故记之。
如果该对象的引用和参数对象的引用相同,返回true。这项测试在成立时能够免去其他所有测试工作。
如果参数为null,返回false(还可以避免在之后的代码中使用空引用)。
如果两个对象的类不同,返回false。要得到一个对象的类,可以使用getClass()方法。可以使用==判断Class类型的对象是否相等,因为同一种类型的所有对象的getClass()一定能够返回相同的引用。
将参数对象的类型从Object转换到Date,因为前一项已经测试已经通过,这种转换必然成功。
如果任意实例变量的值不相同,返回false。
实例类Date如下:
public class Date {
private final int month;
private final int day;
private final int year;
public Date(int m, int d, int y) {
month = m;
day = d;
year = y;
}
public int month() {
return month;
}
public int day() {
return day;
}
public int year() {
return year;
}
public boolean equals(Object x) {
if (this == x) {
return true;
}
if (x == null) {
return false;
}
if (this.getClass() != x.getClass()) {
return false;
}
Date that = (Date) x;
if (this.day != that.day) {
return false;
}
if (this.month != that.month) {
return false;
}
if (this.year != that.year) {
return false;
}
}
}