覆盖 equals 方法时如何指定两个对象?

How do I specify both objects when overriding equals method?

我正在做一个作业,要求我覆盖房子的 equals 方法 class。

说明如下:

Two houses are equal when their building areas are equal and their pool status is the same

到目前为止,这是我写的:

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

另请注意,这假定 mPool 是原始类型或 enum 类型。如果是引用类型,比如String,你可能需要调用它的equals方法,比如

return otherHouse.calcBuildingArea() == calcBuildingArea()
         && otherHouse.mPool.equals(mPool);

甚至更多null-friendly

return otherHouse.calcBuildingArea() == calcBuildingArea()
         && Objects.equals(otherHouse.mPool, mPool);

这个怎么样?

return otherHouse.calcBuildingArea() == this.calcBuildingArea()   
         && otherHouse.mPool == this.mPool