Java中equals方法的完美构造

Java中equals方法的完美构造,第1张

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。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/920161.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存