KaliMa KaliMa - 11 months ago 66
Java Question

Testing for equality with Doubles

In Java, the upper case Double can be null.

However if I have Doubles

and I do this:

if (a.equals(b))

it crashes if one of them is null. Is there a better way to compare them?

Answer Source

The simplest way in Java 7+ is:

Objects.equals(a, b)

If you are using an earlier version of Java, you can use the conditional operator:

(a != null) ? a.equals(b) : (b == null)