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;
        }
    }
    
  • 相关阅读:
    Maven的pom文件依赖提示 ojdbc6 Missing artifact,需要手动下载并导入maven参考
    Maven全局配置文件settings.xml详解(转)
    SpringBoot -- 项目结构+启动流程
    64匹马,8个赛道,找出前4名最少比赛多少场?——最快10次,最慢11次;
    Spring家族主流成员介绍
    java 中文与unicode互转
    Netty的Marshalling编解码器
    解决svn迁移过程中出现:SVN Error: is not the same repository as的问题
    netty入门实例
    Dubbo的使用及原理
  • 原文地址:https://www.cnblogs.com/huangzefeng/p/10493097.html
Copyright © 2011-2022 走看看