简体   繁体   English

覆盖等于方法问题

[英]overriding equals method problems

I'm trying to make a rational numbers class and override the equals and hash code methods. 我试图做一个有理数类,并覆盖等号和哈希码方法。 But my equals is coming back true in cases were its clearly not true ie the numerator and denominator are different. 但是,如果分子和分母不同,则我的对等情况重新成立。 Any idea what could be causing this? 知道是什么原因造成的吗?

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;
}

Here is the problem (if not a typo): 这是问题所在(如果不是拼写错误):

if (num == other.num);{

The semicolon means that the if statement is an empty statement, so its evaluation doesn't really get involved in the equals validation process. 分号表示if语句是一个空语句,因此其评估实际上并未参与equals验证过程。 Just remove the semi colon: 只需删除半冒号即可:

if (num == other.num){

Remove the semicolon on this line, which is acting as the body for the if statement. 删除该行的分号,该分号充当if语句的主体。

if (num == other.num);{

With the semicolon, if the denominators are equal, then true will be returned; 对于分号,如果分母相等,则将返回true ;否则,将返回true the check of the numerators is effectively ignored. 分子的检查实际上被忽略了。

Remove the ; 删除; after if (num == other.num); { if (num == other.num); { if (num == other.num); { , changint it to if (num == other.num) { if (num == other.num); { ,将其更改为if (num == other.num) {

Leaving it there, it basically does nothing after the if , then enters the block : 留在那里,它基本上在if之后不执行任何操作,然后进入代码块:

{
    return true;
}

So it will always return true at that point. 因此,它将始终在该点返回true。

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

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