首页 > 解决方案 > 如何避免 Object.equals 方法的多个 if else 块?

问题描述

我正在尝试实现这一点:

public boolean equals(Object o) {
    if (o == this) {
        return true;
    }
    if ((null == o) || !(o instanceof Document)) {
        return false;
    }
    Document other = (Document) o;
    // compare in a null-safe manner
    if (list == null) {
        if (other.list != null)
            return false;
    } else if (other.list == null)
        return false;
    else if (!(list.size() == other.list.size())
            && !(list.equals(other.list)))
        return false;
    return true;

其中'list'是一个类变量以及对象'o'的一个字段。请注意,对象“o”还有许多其他字段,包括布尔值和集合,我需要比较所有这些字段。我尝试查找相关答案,但其中大多数都推荐与我的场景无关的 switch case 或其他 Java 8 组件。

标签: javaperformanceequals

解决方案


你让事情变得非常复杂。写“等于”是冗长乏味的样板,但你让它变得更长。

public boolean equals(Object o) {
    if (o == this) {
        return true;
    }
    if (!(o instanceof Document)) {
        return false;
    }
    Document other = (Document) o;
    if (!Objects.equals(list, other.list)) {
        return false;
    }
    return true;
}

每个引用字段只需要上面的三行,对于基元类似(不要忘记处理浮点的 NaN)。

您的病情不仅要长得多,而且还缺乏对称性。这使得编写更加困难并且更容易出错。

无论如何,写“等于”不是你应该经常手动做的事情。我推荐使用Lombok,还有更多工具,例如AutoValueEqualsBuilder


推荐阅读