java - 比较分数与 boolean 值

标签 java boolean fractions

所以我的 equals 类有问题

public boolean equals(Object other) {
    if (other.equals(this.numerator) &&  other.equals(this.denominator))
        return true;
    else
        return false;
}

它给出了 9/2 eq 9/2= false 的结果。

(我的其余代码供裁判使用) https://gist.github.com/anonymous/6604f427cc9d17391478

我做错了什么?

我编辑了代码,但仍然处理 boolean 值和 int 的错误

public boolean equals(Object other) {
    if (other.equals(this.numerator) == getNumerator() &&  other.equals(this.denominator)== getDenominator())
        return true;
    else
        return false;
}

最佳答案

实现equals时,在检查对象是否相等之前,您应该考虑以下场景:

  • 这两个实际上是对同一个对象的引用
  • other 对象为 null
  • other 对象是不同类型的实例

并且在检查两个对象之间的相等性时,您还应该考虑比较中涉及的每个字段的空性。在大多数IDE中equals可以自动生成,在eclipse中:

Alt + Shift + s --> Generate hashCode() and equals()

下一个是由eclipse生成的:

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        A other = (A) obj;
        if (denominator == null) {
            if (other.denominator != null)
                return false;
        } else if (!denominator.equals(other.denominator))
            return false;
        if (numerator == null) {
            if (other.numerator != null)
                return false;
        } else if (!numerator.equals(other.numerator))
            return false;
        return true;
    }

关于java - 比较分数与 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124710/

相关文章:

java - 使用 DataSerializable 的 Hazelcast 3.5 序列化

javascript - 宽恕是真也是假

java - 这个句子怎么读,它叫什么

Java - 用一个字节索引到数组

java - 如何向 x 次 TCP 客户端请求 TCP 服务器数据?

java - 查找两个整数中是否有相似的十进制数字

c++ - 在 Rcpp 函数中使用 Bool-Vector 进行子集化(Rcpp 初学者的问题...)

python - 对 IF 语句使用 OR 比较

javascript - 我需要写一个带分数作为假分数

python - Python 中的有理数