0

With the below code, when comparing the Integer value for a given key in a hashmap. at a borderline 126 vs 127, the comparison returns different results. I'm wondering why will java behave this way?

Map<Character, Integer> map1 = new HashMap<>();
Map<Character, Integer> map2 = new HashMap<>();
int n = 127;
for (int i = 0; i < n; i++) {
    map1.put('c', map1.getOrDefault('c', 1)+1);
    map2.put('c', map2.getOrDefault('c', 1)+1);
}
System.out.println(map1.get('c') == map2.get('c')); // print true if n = 126, print false if n = 127
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
Sam He
  • 79
  • 1
  • 8
  • 3
    Does this answer your question? [Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?](https://stackoverflow.com/questions/1700081/why-is-128-128-false-but-127-127-is-true-when-comparing-integer-wrappers-in-ja) – Hanchen Jiang Jan 17 '22 at 20:57
  • 1
    Don't compare objects with `==` only if you want to check identity. – Valerij Dobler Jan 17 '22 at 21:06

1 Answers1

2

This is because it's caching by JVM. In other words for all values [-128; 128). Integer.valueOf(i) will return the same Integer instance.

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35