本文内容来自《Java核心技术》
Java Object 类中的方法用于检测两个对象是否等于另外一个对象。判断方法是判断两个对象是否具有相同的引用。但是这种方法在实际中并不实用,往往需要重写此方法。
编写一个完美equals方法的建议:
- 显示参数命名为otherObject,稍后需要将它转换成另一个对象变量other
- 检测this与otherObject是否引用同一个对象:
if(this == otherObject) return true;
- 检测otherObject是否为null,如果为null,返回false。
if(otherObject == null) return false;
- 比较this 和 otherObject 是否属于同一个类。
- 将otherObject转换为相应的类类型变量。
ClassName other = (ClassName)otherObject;
- 比较所有需要的比较的域。
例如:
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical 第二条
if (this == otherObject) return true;
// must return false if the explicit parameter is null 第3条
if (otherObject == null) return false;
// if the classes don't match, they can't be equal 第四条
if (getClass() != otherObject.getClass()) return false;
// now we know otherObject is a non-null Employee 第五条
Employee other = (Employee) otherObject;
// test whether the fields have identical values 第六条
return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay); }
private String name;
private double salary;
private Date hireDay;
}
提示:
1,第四条中,如果equals的语义在每个子类中有所改变,使用:
if (getClass() != otherObject.getClass()) return false;
如果语义没有改变,使用instanceOf()判断
2,子类中重载equals,需要先调用父类的equals方法:
class Manager extends Employee
{
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
public boolean equals(Object otherObject)
{
if (!super.equals(otherObject)) return false;
Manager other = (Manager) otherObject;
// super.equals checked that this and other belong to the same class
return bonus == other.bonus;
}
private double bonus;
}