【问题标题】:Not sure how to complete this equals method不知道如何完成这个等于方法
【发布时间】:2015-11-14 18:33:25
【问题描述】:

有人可以帮我解决这个问题吗?我已经尝试查找其他示例以查找我需要做的事情并继续遇到称为 EqualsBuilder 的东西,这是我需要使用的吗?如果两个 IF 都不满足,我是否需要再次调用 equals?

以下代码包含一个类定义和一个不完整的方法定义。 equals 方法用于比较建筑物。 如果建筑物具有相同的名称和楼层数(但不一定是相同的建筑物),则返回 true,否则返回 false。

public class Building {      
    private String name;      
    private int noOfFloors;

    public boolean equals (Object rhs) {          
        if (this == rhs) { 
            return true; 
        }          
        if (!(rhs instanceof Building)) { 
            return false; 
        }          
        Building b = (Building) rhs;     

        // missing return statement      
    }  
}

【问题讨论】:

  • 你的问题包含你问题的答案...
  • 比较 this.nameb.namethis.noOfFloorsb.noOfFloors

标签: java equals equals-operator


【解决方案1】:
public boolean equals (Object rhs) {          
    if (this == rhs) { 
        return true; 
    }          
    if (!(rhs instanceof Building)) { 
        return false; 
    }          
    Building b = (Building) rhs;     

    // This is what you're supposed to add. It will return true only if both
    // object's attributes (name and number of floors) are the same
    return this.name.equals(b.name) && this.noOfFloors == b.noOfFloors;
} 

【讨论】:

  • 我也应该这样说,更短:)。只是认为它可能对 OP 来说已经足够详细了。无论如何都值得一票
【解决方案2】:

您现在唯一需要测试的是两个对象的字段。如果它们相等,那么您应该返回 true,如果其中至少一个不相等,那么您应该返回 false。

由于在这种情况下您的字段是intString,因此您可以将== 用于整数字段,将.equals() 用于字符串字段。

这样的事情应该可以很好地完成工作:

if(this.name.equals(b.name) && this.noOfFloors == b.noOfFloors){
    return true ;
}
else{
    return false;
}

【讨论】:

    【解决方案3】:

    在 instanceOf 测试之后,您希望将对象的字段与另一个对象进行比较。像Objects.deepEquals() 这样的东西应该可以很好地为您解决问题。

    【讨论】:

    • 哎呀,意思是deepEquals()
    • 即便如此,也不确定这是要走的路。由于未定义 equals 方法,我非常不确定这会给出什么结果,但无论如何我从不使用 usr deepEquals()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多