覆盖Objects.equals方法

O bject类中的equals方法

源码

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

Object的equals方法判断的仅仅是两个对象是否具有相同的引用,但是对于大多数类来说,这样的比较方式完全没有意义,比如实际中两个学生的学号相等,我们就认为是同个人了。

重写equals方法

1.步骤
(1)检测this与otherObjects是否引用同一个对象
if(this == otherObject) return true;
(2)检测otherObject是否为null,如果为null,返回false
if(otherObject == null) return false;
(3)比较this与otherObject是否属于同一个类。如果equals的语义在每个子类中有所改变,就使用getClass检测:
if(getClass != otherObject.getClass()) return false;
如果所有的子类都拥有统一的语义,就使用instanceof检测:
if(!(otherObject instanceof ClassName)) return false;
(4)将otherObject转换为相应的类类型变量:
ClassName other = (ClassName)otherObject;
(5)对所有需要比较的域进行比较,使用==比较基本类型域,使用equals比较对象域,如果所有域都匹配,就返回true,否则返回false。
(6)如果在子类中重新定义equals,就要在其中包含调用super.equals(other)

2.例子
(1)实体:

public class Employee {
    private String name; //姓名
    private double salary; //薪水
    
    public Employee(){
    }
    
    public Employ(String name,double salary){
      this.name = name;
      this.salary = salary;
    }
    //setter & setter
}

public class Manager extends Employee{
    private double bonus; //奖金
    
    //setter & getter
}

(2)equals方法
Employee:

public class Employee
{
    ...
    public boolean equals(Object otherObject){
    if(this == otherObject) return true;
    if(otherObject == null) return false;
    if(getClass() != otherObject.getClass)               return false;
    Employ other = (Employee)otherObject;
    return Objects.equals(name,other.name)
           && salary == other.salary;
    }
}

name的比较中不要使用name.equals(other.name),因为name可能为空,就会异常。

Manager:

public class Manager
{
    ...
    public boolean equals(Object otherObject){
    if(!super.equals(otherObject)) return false
    Manager other =(Manager)otherObject;
    return bonus == other .bonus;
    }
}
posted @ 2019-03-07 22:34  WongJeffung  阅读(527)  评论(0编辑  收藏  举报