为Java类创建相等的方法来比较double或int值
我的家庭作业是创建一个类的equal方法,该方法在Java中重写对象类的equal方法。我的代码如下所示,但讲师评论道:“不能将double与==,!=进行相等比较,因为存储不精确。”那么,在这种情况下,如何相应地编辑代码?非常感谢你。 类游戏设置{
private int firingInterval;
private double moveSpeed;
...
public boolean equals(Object obj) {
//objects are equal if same firingInterval and moveSpeed
GameSettings other;
boolean result = false;
//TODO
other = (GameSettings) obj;
if (obj instanceof GameSettings) {
return (firingInterval == other.getFiringInterval()
&& moveSpeed == other.getMoveSpeed());
} else {
return result;
}
}
# 1 楼答案
正如你的讲师所说,比较double并不是简单地使用equals运算符。例如,你可以尝试1不等于1.000
相反,我们经常使用两个值之间的差值来比较double。如果delta相对较小,那么这些值将相等