java重写等于方法问题
我试图创建一个有理数类并重写equals和hash代码方法。但我的等式在明显不成立的情况下(分子和分母不同)又变为真。你知道这是什么原因吗
public boolean equals(Object rhs) {
if (this == rhs){
return true;
}
if (rhs == null){
return false;
}
if (!(rhs instanceof Rational)){
return false;
}
Rational other = (Rational) rhs;
if (denom == other.denom){
if (num == other.num);{
return true;
}
}
return false;
}
# 1 楼答案
删除此行的分号,该分号充当
if
语句的主体使用分号,如果分母相等,则返回
true
;实际上忽略了对分子的检查# 2 楼答案
删除
if (num == other.num); {
之后的;
,将其改为if (num == other.num) {
把它留在那里,它在
if
之后基本上什么也不做,然后进入块:因此,在这一点上,它将始终返回true
# 3 楼答案
问题是(如果不是打字错误):
分号意味着
if
语句是一个空语句,因此它的求值实际上不涉及equals验证过程。只需删除分号: