为类编写完美的Equals()

来源:互联网 发布:java代码实现阶乘 编辑:程序博客网 时间:2024/06/13 22:38

1 显式参数命名为otherObject,稍后需要将他转换成另一个叫做other的变量。

2 检测this与ohterObject是否引用同一个对象:

    if(this==otherObject) return true;
    这条语句只是一个优化,实际上,这是一种经常采用的形式,因为计算这个等式要比一个一个比较类中的成员域的开销小的多。

3 检测otherObject 是否为null,如果为null,返回false。此项检测非常必要。

     if(otherObject == null) return false;
4 比较this与otherObject是否属于同一个类。如果equals的语义在每个子类着哦功能所有改变,就是用getClass检测:

     if(getClass() != otherObject.getClass()) return false;
如果所有的子类都拥有统一的语义,则使用instanceof检测。

    if( !(otherObject instaanceof ClassName) ) return false;

5 将otherObject 转换为相应的类类型变量:

    ClassName other = (ClassName) otherObject;
6 现在开始需要对所有的类的成员域进行比较了。使用==比较基本类型成员域,使用equals比较对象成员域。如果所有的域都匹配就返回true,否则返回false。

 return ( filed1 == other.field1 &&          filed2 == other.field2 &&          filed3.equals(other.field3)         );

如果在子类中重新定义equals,就要在其中哦功能包含调用
super.equals(other);


综合:

 public boolean equals(Object otherObject){    //a quick test to see if the objects are idnetical    if(this == otherOtherject) return true;  //must return false if the explicit parameter is null    if(otherObject == null) return false;  // if the class do not match, htey can not be equal    if(getClass() != otherOgject.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.salary  &&             hireDay.equals(other.hireDay) );}


0 0