Java Long Value Cacheing

The cache size may be controlled by -XX:AutoBoxCacheMax=<size> option.

  1. == compares references, equals compares value. Comparing Long values should use the latter.

  2. Another way is to use longA.compareTo(longB) == 0

  3. 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);
     }
    
  4. 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.

References

  1. what-are-not-2-long-variables-equal-with-operator-to-compare-in-java

  2. Integer wrapper class and == operator - where is behavior specified?

  3. Compare two long values

  4. Why Integer class caching values in the range -128 to 127?

Tags:

Posted: