有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

简化Java布尔比较

我找到了一个方法,可以比较两个动作,我想把它简化

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) 个答案

  1. # 1 楼答案

    您可以使用apachecommons中的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();
        }
    
  2. # 2 楼答案

    如果要将三元运算符写入一行,可以使用三元运算符:

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