Double.equals pitfalls

It turns out that Double.equals is not always the same as == with two double primitives. Case in point:

double a = Double.NaN;
System.out.println(a == a);
Double b = new Double(a);
System.out.println(b.equals(b));

This code will print out false and true.

What’s going on? Basically, if you look at the Javadoc for the equals method, it says that “two double values are considered to be the same if and only if the method doubleToLongBits(double) returns the identical long value when applied to each.”

The reverse behavior occurs for positive and negative zero. == will return true, but Double.equals will return false.

Post a Comment

Your email is never shared. Required fields are marked *

*
*