有没有一种方法可以简化此代码,比较两个点与字段x和y的相等性?

问题描述

是否有一种方法可以简化下面的代码,该代码旨在比较两个点与字段x和y的相等性?

public class Point {
    private int x;
    private int y;

    public Point(int x,int y) {
        this.x = x;
        this.y = y;
    }

    public boolean equals(Object o) {
        if (o instanceof Point) {
            Point c = (Point) o;
            if (!(c.x == this.x && c.y == this.y)) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}

解决方法

我相信以下是最简单的

public boolean equals(Object o) {
    if (o == null || o.getClass() == getClass()) return false;
    return x == ((Point) o).x && y == ((Point) o).y;
}

希望对您有帮助!

,

这可以简化为:

@Override
public boolean equals(Object o) {
    if (!(o instanceof Point)) {
        return false;
    }
    Point c = (Point) o;
    return x == c.x && y == c.y;
}

说明

用布尔值本身的结果(或否定结果)替换条件中返回 true/false 的 if/then 布尔条件更短而且通常更清晰。

例如:

if (someBooleanCondition()) { return true; } else { return false; }

可以简化为

return someBooleanCondition();

将此应用于您的示例:

if (!(c.x == this.x && c.y == this.y)) {
    return false;
} else {
    return true;
}

变成:

return c.x == this.x && c.y == this.y;

我首先检查了 instanceof,因为我觉得返回异常情况的短路会导致更容易阅读代码,尽管这是主观的。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...