微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决有没有一种方法可以简化此代码,比较两个点与字段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,因为我觉得返回异常情况的短路会导致更容易阅读代码,尽管这是主观的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。