我正在尝试创建一个有理数类并覆盖 equals 和 hash code 方法。但如果分子和分母不同,则我的等式会返回正确的情况,即分子和分母不同。知道是什么原因造成的吗?
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;
}
最佳答案
这是问题所在(如果不是拼写错误):
if (num == other.num);{
分号意味着 if
语句是一个空语句,因此它的计算并不真正参与等于验证过程。只需删除分号即可:
if (num == other.num){
关于java - 重写 equals 方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21689370/