javaequalsprimitiveautoboxing

Comparing "long" and "Long"


I want to compare a long value (primitive type) with another Long value (wrapper type):

long x = 5;
Long y = 5L;

// version 1: only safe, if x is a primitive type
var isEqual = x == y;

// version 2: y needs to be converted to its primitive type
var isEqual = x == y.longValue();

// version 3: using Object.equals(), x will be converted to its wrapper type
var isEqual = Objects.equals(x, y);

The question is: Is there any benefit in using version 2 instead of version 3?


Solution

  • The advantage of Objects.equals(x, y) is that it covers null cases. The first two would throw a NPE if the Long variable is null.

    On the other hand, Objects.equals(x, y) would autobox the long (primitive) argument, hence creating an object. But normally this shouldn't be a concern.

    So: just Objects.equals() because the comparison involves a wrapper object and to keep the code simple and readable, otherwise just check for nullability before comparing primitives with Long.longValue().