corejava_笔记09_equals方法重写_p.166

package equals;

import java.time.*;
import java.util.Objects;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate 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
      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 Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
   }

   public int hashCode()
   {
      return Objects.hash(name, salary, hireDay); 
   }

   public String toString()
   {
      return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
            + "]";
   }
}

Object类中的equals方法用于检测一个对象是否等于另外一个对象。即判断两个对象是否具有相同的引用(空间地址)。

    public boolean equals(Object obj) {
        return (this == obj);
    }

但有的时候,我们只需要比较两个对象的状态是否相等(例如,String类中的字符串内容是否相同),这时,我们需要重新equals方法。重写方法参见红色代码。

    注:为防备name或hireDay可能为null的情况,需要调用Objects.equals方法。如果两个参数都为null,Objects.equals(a,b)调用将返回true;如果其中一个参数为null,则返回false;否则,如果两个参数都不为null,则调用a.equals(b)。可以将Employee.equals方法的最后一句改写为

return Objects.equals(name,other.name)
&&salary ==other.salary
&&Object.equals(hireDay,other.hireDay);

猜你喜欢

转载自blog.csdn.net/weixin_42439582/article/details/80810904