覆盖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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值