简化Java布尔比较

时间:2014-04-04 15:53:04

标签: java boolean equals

我发现一个方法等于比较两个移动,我想简化它。

    public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Move other = (Move) obj;
    return !(this.initialBalls != other.initialBalls &&
            (this.initialBalls == null || !this.initialBalls.equals(other.initialBalls)))
            && this.direction == other.direction && this.color == other.color;
}

有人有想法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用Apache Commons的EqualsBuilder

public boolean equals(Object obj) {
    if (obj == null) { return false; }
    if (obj == this) { return true; }
    if (obj.getClass() != getClass()) {
        return false;
    }
    Move rhs = (Move) obj;
    return new EqualsBuilder()
        .appendSuper(super.equals(obj))
        .append(initialBalls, rhs.initialBalls)
        .append(direction, rhs.direction)
        .append(color, rhs.color)
        .isEquals();
    }

答案 1 :(得分:0)

如果要在一行中编写,可以使用三元运算符:

return (obj == null || getClass() != obj.getClass()) ? false : [TODO: check if they are equal];