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?
y
isnull
. V3 will boxx
toLong
and do aLong
vsLong
comparison, hence supportnull
correctly and wont throw. – SunburnLong x = 200L; Long y = 200L; var isEqual = x == y;
returned false. – Lynwoodlynxx
along
. Andlong == Long
leads to unwrapping conversion to getlong == long
, which the compiler does by callinglongValue()
. So V1 and V2 are identical after compilation (with the types you have in your question). – SunburnLong == Long
(you did not do this here, but I am still noting it) can lead to undesired results sinceLong
instances are not cached for the full range. – Sunburn==
. 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==
between boxes safe. See here for example. – Doha