Comparing "long" and "Long"
Asked Answered
L

1

10

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?

Lynwoodlynx answered 10/11, 2021 at 10:53 Comment(7)
They are all more or less identical. In particular V1 and V2 are the same after compilation (check their bytecode). Be careful with V1 and V2 who will both throw a NPE if y is null. V3 will box x to Long and do a Long vs Long comparison, hence support null correctly and wont throw.Sunburn
Imagine, x is also a LONG (and not a long), then version 1 would not be correct, because Long x = 200L; Long y = 200L; var isEqual = x == y; returned false.Lynwoodlynx
Well, yeah. But you specifically made x a long. And long == Long leads to unwrapping conversion to get long == long, which the compiler does by calling longValue(). So V1 and V2 are identical after compilation (with the types you have in your question).Sunburn
As a minor side note, comparing Long == Long (you did not do this here, but I am still noting it) can lead to undesired results since Long instances are not cached for the full range.Sunburn
@nimo23, @Zabuzard: I think that you are both right! Zabuzard is right that in this case it is perfectly safe to compare with ==. But I think nimo23 is right in that even if it is safe, it is a bit hard to understand and easy to make mistakes when using == with boxes. So it's better to avoid it altogether!Doha
Side note: In Project Valhalla the Java developers are working on a way to unify boxes with primitives. This will, among other things, make comparitions using == between boxes safe. See here for example.Doha
Thanks. I made some corrections.Lynwoodlynx
P
12

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().

Prather answered 10/11, 2021 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.