equals使用

来源:互联网 发布:淘宝女装卖家自制影棚 编辑:程序博客网 时间:2024/06/06 02:52

1:在object类中,equals方法判断两个对象是否具有相同的引用;然而对大多数对象来说,如果两个对象的状态相对,就认为两个对象时相等的;

class Employ{    public boolean equals(Object otherObject){        if(this==otherObject)  return object;        if(otherObject==null) return false;        if(getClass()!=otherObject.getClass()) return false;        Employee other=(Employee) otherObject;        return name.equals(other.name)&&salary==other.name&&            hireDay.equals(other.hireDay);    }}

*getClass方法将返回一个对象所属的类;

问题1:在子类定义equals方法,首先调用超类的equals方法。如果检测失败,那么对象就不可能相等;如果超类中的域相等,就需要比较子类中的实例域;

class Manager extends Empolyee{...    public boolean equals(Object otherObject){    //核对this与otherObject属于同一类        if(!super.equals(otherObject)) return false;        Manager other=(Manager) otherObject;        return bonus==other.bonus;    }}

问题2:

//不能解决otherObject是this的子类情况if(!(otherObject instanceof Employee)) return false;

Java语言规范要求equals方法具有下面的特性:
1) 自反性: x.equals(x)
2) 对称性: x.equals(y) y.equals(x)
3) 传递性 : x.equals(y) y.equals(z) x.equals(x)
4) 反复性:
5) x.equals(null)

*instanceof 考虑到 e.equals(m) 与m.equals(e) 报错

问题3:对于AbstractSet类的equals方法,将检测两个集合是否有相同的元素;是一个相当特殊的类;

问题4:
**如果子类能够用于自己相等的概念,则对称性需要将强制采用getClass进行检测;
如果由超类决定相等的概念,那么就可以使用instanceof 进行检测,这样可以在不同子类的对象之间进行相等的比较。**

在雇员和经理的例子中,只要对应的域相等 ,就可以认为两个对象相等;如果两个Manager对象所对应的姓名,薪水,和雇佣日期均相等,而奖金不相等,就认为它们是不相等,因此可以使用getClass检测;假设使用雇员的ID作为相等的检测标准,并且这个相等的概念适用于所有的子类,就可以使用instanceof进行检测,并且应该将Employee.equals声明为final;***

2:编写equals方法的建议
1)显示参数命名为otherObject,稍后需要将它转称另一个叫作other的变量;
2)检测this与otherObject是否引用同一个对象: if(this==otherObject) return ture;
3)检测otherObject是否为null,如果为null,返回为false. if(otherObject==null) return false;
4) 比较this与otherObject是否属于同一个类。
如果equals的语句在每一个子类中有所改变,就使用getClass检测;

if(getClass()!=otherObject.getClass()) return false;

如果所有的子类都拥有同一的语义,就使用instanceof检测

if(otherObject instanceiof ClassName) return false;

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

ClassName other=(ClassName) otherObject;

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

 return field1==other.field1 &&  field2 .equals(other.field2)  &&  ..

如果在子类中重写定义equals,就要在其中包含调用super.equals(other)。

对于数组类型的域,就要在其中静态的Arrays.equals方法检测相应的数组元素是否相等;

0 0
原创粉丝点击