所以我的 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/