• 覆盖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;
        }
    }
    
  • 相关阅读:
    《VC驿站《PE文件格式解析》》
    《逆向分析教程》
    《逆向工程核心原理.pdf【2】》
    《逆向工程核心原理.pdf》
    一个完整的机器学习项目在Python中的演练(一)
    粒子群优化算法(PSO)之基于离散化的特征选择(FS)(三)
    Tensorboard详解(下篇)
    Tensorboard 详解(上篇)
    基于Doc2vec训练句子向量
    使用Keras进行深度学习:(七)GRU讲解及实践
  • 原文地址:https://www.cnblogs.com/huangzefeng/p/10493097.html
Copyright © 2020-2023  润新知