重写equals()方法(idea生成的高效方法)

equals 方法
Object 类中的 equals 方法用于检测一个对象是否等于另外一个对象。在 Object 类中,这
个方法将判断两个对象是否具有相同的引用。如果两个对象具有相同的引用, 它们一定是相
等的。从这点上看,将其作为默认操作也是合乎情理的。然而,对于多数类来说, 这种判断
并没有什么意义。例如, 采用这种方式比较两个 PrintStream 对象是否相等就完全没有意义。
然而, 经常需要检测两个对象状态的相等性,如果两个对象的状态相等, 就认为这两个对象
是相等的。
例如, 如果两个雇员对象的姓名、 薪水和雇佣日期都一样, 就认为它们是相等的(在实
际的雇员数据库中,比较 ID 更有意义。利用下面这个示例演示 equals 方法的实现机制)。

public class Employee
public boolean equals(Object othe「Object)
{
// 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 (getClassO != otherObject.getClass())
return false;
// now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// test whether the fields have identical values
return name.equals(other. name)
&& salary = other,sal ary
&& hi reDay. equals(other,hi reDay):
  }
}

 

 

 

posted @ 2021-08-25 15:29  小白冲  阅读(613)  评论(0编辑  收藏  举报