3 ms·
Java: jshell> Long a = 12l; Long b = 12l; a ==> 12 b ==> 12 jshell> a == b $3 ==> true jshell> a = 54321l; b = 54321l; a ==> 54321
by croo 6y ago
Java:
jshell> Long a = 12l; Long b = 12l;
a ==> 12
b ==> 12
jshell> a == b
$3 ==> true
jshell> a = 54321l; b = 54321l;
a ==> 54321
b ==> 54321
jshell> a == b
$6 ==> false
¯\_(ツ)_/¯
- gtsteve 6y agoReally? Not being a Java guy, what is the explanation for this? Terms like boxing and reference comparison come to mind but I can't stitch them into a narrative to explain this.
- Twisol 6y ago`Long` is a boxed (reference) type, but small numbers are interned so you get the same reference when boxing a primitive value. Larger numbers aren't interned, so you get fresh boxes. https://stackoverflow.com/questions/1700081/why-is-128-128-false-but-127-127-is-true-when-comparing-integer-wrappers-in-ja https://stackoverflow.com/questions/1700081/why-is-128-128-f...
- croo 6y agoReference comparison it is with a twist: the jvm caches the most common integers. You'll get the same object from -128 to +127 when implicitly assigning value. This is part of the spec, and can be set to a larger pool with -XX:AutoBoxCacheMax (but cannot be turned off). If you explicitly ask for a new object (Long a = new Long(123l);) you will get a new object and the comparison will fail as expected. The moral of the story is to always use .equals().