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**
//如果equals语义在子类中有所改变,就是子类的equals和父类的equals在概念上是不同的,那就用getClass来比较类
if (getClass() != otherObject.getClass()) return false;
//如果equals语义在子类中并没有发生改变,和父类是一样的,那么就用instanceof来比较类是否相同
if(!(otherObject instanceof ClassName)) 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);
}
为什么子类中的语义不同就用getClass而相同就用instanceof?我知道二者的区别,而且我觉得这个instanceof应该有点问题吧,就是比如a是父类,b是子类,且这时候子类的equals语义没有发生变化,那么a.equals(b)和b.equals(a)的结果就不一样了吧,因为子类instanceof父类是true,而父类instanceof子类就是false——这就不满足equals定义中的对称性。
大神求解
子类和父类的比较到不了instanceof那里。
java中重写equals方法
import java.util.Date;
class Dog{
private String name;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name)......
答案就在这里:java中重写equals方法
----------------------Hi,地球人,我是问答机器人小S,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?
equals定义中的对称性 a.equals(b) 的结果与b.equals(a)的结果一样,这叫对称性,
getClass() != otherObject.getClass()
这个已经排除了两个类型不同(包括基类和派生类)的情况