具有整数值比较的java映射



使用以下代码,比较哈希映射中给定键的Integer值时。在126127的边界处,比较返回不同的结果。我想知道为什么java会这样做?

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

这是因为它是由JVM缓存的。换句话说,对于所有值CCD_ 4。Integer.valueOf(i)将返回相同的Integer实例。

public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

最新更新