I'm overriding an equality method for an object. Let's say an odometer with a km variable stored as a double (along with some other variables not important for the example).
public class Odometer {
private double km;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(km);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Odometer other = (Odometer) obj;
if (Double.doubleToLongBits(km) != Double.doubleToLongBits(other.km))
return false;
return true;
}
}
Now, the comparison for the double variable as generated by Eclipse (along with the hash code) is an exact bit-wise comparison. However, I've been told to use a "epsilon" difference when comparing float or double values. I've even heard it phrased as "never use equality when comparing floats."
boolean equals(double x, double y, double epsilon) {
return x - y < epsilon;
}
The JUnit assertEquals
method for doubles bears this out:
assertEquals(double expected, double actual, double epsilon)
So, which comparison should I use here?