Java 编写一个完美的equals()方法的建议

本文内容来自《Java核心技术》

Java Object 类中的方法用于检测两个对象是否等于另外一个对象。判断方法是判断两个对象是否具有相同的引用。但是这种方法在实际中并不实用,往往需要重写此方法。

编写一个完美equals方法的建议:

  1. 显示参数命名为otherObject,稍后需要将它转换成另一个对象变量other
  2. 检测this与otherObject是否引用同一个对象:
    if(this == otherObject) 
             return true;  

             
  3. 检测otherObject是否为null,如果为null,返回false。
    if(otherObject == null)
              return false;

  4. 比较this 和 otherObject 是否属于同一个类。
  5. 将otherObject转换为相应的类类型变量。
    ClassName other = (ClassName)otherObject;

  6. 比较所有需要的比较的域。

例如:

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值