Java 重写equals方法时,如何指定这两个对象?
我正在做一项作业,要求我重写house类的equals方法 说明如下: 当两栋房屋的建筑面积相等且其水池状态相同时,这两栋房屋是相等的 到目前为止,我一直在写:Java 重写equals方法时,如何指定这两个对象?,java,android,overriding,equals,Java,Android,Overriding,Equals,我正在做一项作业,要求我重写house类的equals方法 说明如下: 当两栋房屋的建筑面积相等且其水池状态相同时,这两栋房屋是相等的 到目前为止,我一直在写: @Override public boolean equals(Object other) { if (other instanceof House) { House otherHouse = (House) other; return otherHouse.calcBuildingArea()
@Override
public boolean equals(Object other) {
if (other instanceof House) {
House otherHouse = (House) other;
return otherHouse.calcBuildingArea() == ???
&& otherHouse.mPool == ???
} else {
return false;
}
}
现在我不知道在==符号之后写什么。我不知道如何指定调用该方法的对象。如果在未指定对象的情况下调用方法,则将在当前对象上调用该方法。这样你就可以写作了
return otherHouse.calcBuildingArea() == calcBuildingArea()
&& otherHouse.mPool == mPool;
return otherHouse.calcBuildingArea() == this.calcBuildingArea()
&& otherHouse.mPool == this.mPool;
或者,如果你想让它变得清晰明了,你可以写
return otherHouse.calcBuildingArea() == calcBuildingArea()
&& otherHouse.mPool == mPool;
return otherHouse.calcBuildingArea() == this.calcBuildingArea()
&& otherHouse.mPool == this.mPool;
还要注意,这假定mPool是基元类型或枚举类型。如果它是一个引用类型,比如String,您可能需要调用它的equals方法,比如
return otherHouse.calcBuildingArea() == calcBuildingArea()
&& otherHouse.mPool.equals(mPool);
甚至是更友好的
return otherHouse.calcBuildingArea() == calcBuildingArea()
&& Objects.equals(otherHouse.mPool, mPool);
这个怎么样
return otherHouse.calcBuildingArea() == this.calcBuildingArea()
&& otherHouse.mPool == this.mPool
你可以使用this关键字引用当前对象。你能告诉我你将如何写这行吗?我对此有点陌生……谢谢你应该检查其他房子是否真的是房子。@Chieftwo Pencils做这个特殊检查的代码已经在问题中了。OP只想知道在这条线上写些什么???问题中的分数。这个答案是正确的。@ChiefTwoPencils我刚才在回答Pshemo关于在???的地方应该放什么的具体问题???。这个代码已经在if块中,以确保另一个是房子。我没有说它是错误的@DavidWallace;我提出了一些建议。当有人问这样一个基本的问题时,也许建议他们提出的替代方案是合适的;令人吃惊的回答