public boolean equals(Object otherObject){
if (this==otherObject)
return true;
if (otherObject==null)
return false;
if (this.getClass()!=otherObject.getClass())
return false;
//上面的判断已经将不是同一种类型的直接return false了,下面为何还要继续比较判断啊?
ComplexNumber other =(ComplexNumber)otherObject;
if (re==other.re && im==other.im)
return true;
else
return false;
}
if (this==otherObject)
return true;
if (otherObject==null)
return false;
if (this.getClass()!=otherObject.getClass())
return false;
//上面的判断已经将不是同一种类型的直接return false了,下面为何还要继续比较判断啊?
ComplexNumber other =(ComplexNumber)otherObject;
if (re==other.re && im==other.im)
return true;
else
return false;
}
第二个if 任何一个对象实例不能equals false
第三个if 不是同一个类型返回false。
接下来转型,判断数据成员的相等与否
if (this==otherObject)
return true;
if (otherObject==null)
return false;
if (this.getClass()!=otherObject.getClass())
return false;}这样为什么会错?
逻辑问题如果不是同一类型return false,如果是,还要继续判断,SO。。
指不定哪个return会被执行 ,所以都要写
if (this==otherObject) //比较this和otherObject的地址是否一样
return true;
if (otherObject==null) //判断otherObject是否为null
return false;
if (this.getClass()!=otherObject.getClass()) //判断类型是否一样
return false; //上面的判断已经将不是同一种类型的直接return false了,下面为何还要继续比较判断啊?(这个跟下面的代码完全没有冲突)
//因为如果上面判断是同一类型,才需要进一步判断内容是否也一样,如下
ComplexNumber other =(ComplexNumber)otherObject;
if (re==other.re && im==other.im)
return true;
else
return false;
}