Java Long Value Cacheing
The cache size may be controlled by -XX:AutoBoxCacheMax=<size> option.
-
==compares references,equalscompares value. Comparing Long values should use the latter. -
Another way is to use
longA.compareTo(longB) == 0 -
LongCache[-128,127], which means Long value between -128 to 127 would return same object, because it run
Long.valueOf(String)internally.public static Long valueOf(long l) { final int offset = 128; if (l >= -128 && l <= 127) { // will cache return LongCache.cache[(int)l + offset]; } return new Long(l); } -
Same reason, it has IntegerCache
public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); }
Conclusion:
Should use .equals() as much as possible for Objects comparing; leave >=< to primitive types.