I have double types within my class and have to override equals()/hashCode(). So I need to compare double values.
Which is the correct way?
Version 1:
boolean isEqual(double a, double b){
return Double.doubleToLongBits(a) == Double.doubleToLongBits(b);}
Version 2:
boolean isEqual(double a, double b){
final double THRESHOLD = .0001;
return Math.abs(a - b) < THRESHOLD;
}
Or should I avoid primitive double
at all and use its wrapper type Double
? With this I can use Objects.equals(a,b)
, if a
and b
are Double.