栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java中equals方法的完美构造

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中equals方法的完美构造

equals方法的完美构造 1、equals方法 Object.equals()方法用于检测一个对象是否等于另一个对象,这种方法用来确定两个对象的引用是否相等。它的默认行为是比较二者的引用是否相等,这对于大多数类来说或许已经足够了,但是在实际过程中我们对于相等有各自不同的描述,例如在员工系统中员工可能存在多个身份,这种时刻我们比较员工的id或许才更有意义,我们先看下面的示例代码,来对这种过程进行一些基本的理解。
  public boolean equals(Object otherObject)
   {
      // a quick test to see if the objects are identical
      if (this == otherObject) return true;

      // must return false if the explicit parameter is null
      if (otherObject == null) return false;

      // if the classes don't match, they can't be equal
      if (getClass() != otherObject.getClass()) return false;

      // now we know otherObject is a non-null Employee
      var other = (Employee) otherObject;

      // test whether the fields have identical values
      return name.equals(other.name)
         && salary == other.salary && hireDay.equals(other.hireDay);
   }

这里有一些小问题,比如name可能存在是null的情况,如果参数为null,我们调用**name.equals()会产生空指针引用从而产生一些错误,所以要避免这种情况发生,我们使用Object.equals(name,other.name)**来解决这个问题。

  这里我们定义了一个工作员工的类,员工有很多的属性可以提供给我们使用,在员工类中,有薪水,名字,雇佣日期等各种属性。我们在equals方法的检测中主要进行了如下的几个步骤。
  1. 对我们的引用进行检测,如果引用是相等的,那么我们就可以说明它们是相等的。

  2. 如果输入的显示参数为null,我们就返回false

  3. 最后我们将显式参数强制转化为一个名为other的变量,再根据相等类型的要求对基本字段进行判断。

上面的这段代码有一些小问题,比如name可能存在是null的情况,如果参数为null,我们调用**name.equals()**会产生空指针引用 从而产生一些错误,所以要避免这种情况发生,我们使用 Object.equals(name,other.name)来解决这个问题。

2.对于equals构造方法的建议
  1. 显示参数命名为otherObject,稍后将它强制转换为另一个名为other的变量。

  2. 检测this与otherObject是否相等
    if(this ==otherObject) return ture;

  3. 检测otherObject是否为null,如果为null,返回false

  4. 比较this与otherObject的类,如果equals的语义可以在子类中改变,就使用getClass
    if(getClass()!=otherObject.getClass()) return false;
    如果所有的子类都有相同的语义,则使用instanceof
    if(!OtherObject instanceof ClassName)) return false;

  5. 将其强制转化为相应类型的类

  6. 根据相等性概念比较相应的字段

  public boolean equals(Object otherObject)
   {
      // a quick test to see if the objects are identical
      if (this == otherObject) return true;

      // must return false if the explicit parameter is null
      if (otherObject == null) return false;

      // if the classes don't match, they can't be equal
      if (!(otherObject instanceof ClassName) return false;

      // now we know otherObject is a non-null Employee
      var other = (Employee) otherObject;

      // test whether the fields have identical values
      return Objects.equals(name, other.name) 
         && salary == other.salary && Objects.equals(hireDay, other.hireDay);
   }
结论

以上这些就是对equals()方法构造的理解和建议,我们经常要判断二者是否相等,所以这很重要,随笔的参考书籍为java核心技术卷I。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/877093.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号