编写一个完美的 equals 方法的建议 :
1 ) 显式参数命名为 otherObject , 稍后需要将它转换成另一个叫做 other 的变量 。
2 ) 检测 this 与 otherObject 是否引用同一个对象 :
if ( this = otherObject ) return true ;
这条语句只是一个优化。 实际上 , 这是一种经常采用的形式 。 因为计算这个等式要比一个一个地比较类中的域所付出的代价小得多 。
3 ) 检测 otherObject 是否为 null , 如 果 为 null , 返 回 false。 这项检测是很必要的 。
if ( otherObject = null ) return false ;
4 ) 比较 this 与 otherObject 是否属于同一个类。 如果 equals 的语义在每个子类中有所改变, 就使用 getClass 检测 :
if ( getClass ( ) ! = otherObject . getCIassO ) return false ;
如果所有的子类都拥有统一的语义, 就使用instanceof 检测 :
if ( ! ( otherObject instanceof ClassName ) ) return false ;
5 ) 将 otherObject 转换为相应的类类型变量 :
ClassName other = ( ClassName ) otherObject
6 ) 现在开始对所有需要比较的域进行比较了 。 使用 = 比较基本类型域 , 使用 equals 比较对象域。 如果所有的域都匹配 , 就返回true ; 否 则 返 回 false。
return fieldl = = other.field && Objects.equa 1 s ( fie 1 d 2 , other . field 2 ) && ...;
@Override
public boolean equals(Object other) {
// a quick test to see if the objects are identical
if(other == this){
return true;
}
// must return false if the explicit parameter is null
if(other == null){
return false;
}
// if the classes don ' t match , they can ' t be equal
if(other.getClass()!= this.getClass()){
return false;
}
// now we know other is a non - null Student
Student s = (Student)other;
// test whether the fields have identical values
/*
* 为了防备 name 或 hireDay 可能为 null 的情况 , 需要使用 Objects . equals 方法。如果两个参数都为 null ,
* Objects . equals ( a, b )调用将返回 true ; 如果其中一个参数为 null ,则返回 false ;
*/
//return (this.major.equals(s.major));//this.major 可能为null
return (Objects.equals(this.major, s.major));
}