有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

共 (3) 个答案

  1. # 1 楼答案

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

    if (num == other.num);{
    

    使用分号,如果分母相等,则返回true;实际上忽略了对分子的检查

  2. # 2 楼答案

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

    把它留在那里,它在if之后基本上什么也不做,然后进入块:

    {
        return true;
    }
    

    因此,在这一点上,它将始终返回true

  3. # 3 楼答案

    问题是(如果不是打字错误):

    if (num == other.num);{
    

    分号意味着if语句是一个空语句,因此它的求值实际上不涉及equals验证过程。只需删除分号:

    if (num == other.num){