gpt4 book ai didi

java - 不确定如何完成这个 equals 方法

转载 作者:行者123 更新时间:2023-11-29 03:06:05 25 4
gpt4 key购买 nike

有人可以帮我解决这个问题吗?我已经尝试查找其他示例以找到我需要做的事情并不断遇到名为 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
}
}

最佳答案

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

关于java - 不确定如何完成这个 equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32129725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com