繁体   English   中英

覆盖等于方法问题

[英]overriding equals method problems

我试图做一个有理数类,并覆盖等号和哈希码方法。 但是,如果分子和分母不同,则我的对等情况重新成立。 知道是什么原因造成的吗?

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语句是一个空语句,因此其评估实际上并未参与equals验证过程。 只需删除半冒号即可:

if (num == other.num){

删除该行的分号,该分号充当if语句的主体。

if (num == other.num);{

对于分号,如果分母相等,则将返回true ;否则,将返回true 分子的检查实际上被忽略了。

删除; if (num == other.num); { if (num == other.num); { ,将其更改为if (num == other.num) {

留在那里,它基本上在if之后不执行任何操作,然后进入代码块:

{
    return true;
}

因此,它将始终在该点返回true。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM