zoukankan      html  css  js  c++  java
  • 覆盖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;
        }
    }
    
  • 相关阅读:
    Spring笔记②--各种属性注入
    Spring笔记①--helloworld
    Structs2笔记③--局部类型转换案例
    Struct2笔记②--完善登陆代码
    Structs2笔记①--structs的背景、structs2框架的意义、第一个helloworld
    软件项目的开发之svn的使用
    Java基础第一节.Java简介
    Hibernate笔记④--一级二级缓存、N+1问题、saveorupdate、实例代码
    Hibernate笔记③--集合映射、组合映射、联合主键、查询案例
    Hibernate笔记②--hibernate类生成表、id生成策略、级联设置、继承映射
  • 原文地址:https://www.cnblogs.com/huangzefeng/p/10493097.html
Copyright © 2011-2022 走看看