Return 使用两个不同的 HashMap 检查相同的 Integer 值时为 false

Return false when checking same Integer value using two different HashMap

我不明白为什么当 HashMap 键是 2

时打印错误
Map<Integer, Integer> first = new HashMap<Integer, Integer>();

Map<Integer, Integer> second = new HashMap<Integer, Integer>();

first.put(1, 10);
second.put(1, 10);

first.put(2, 155);
second.put(2, 155);

for (int i = 1; i <= 2; i++) {
    System.out.print("first=" + first.get(i) + "," + "second="
            + second.get(i) + " ");
    System.out.println(first.get(i) == second.get(i));

}

结果

first=10,second=10 true
first=155,second=155 false

这就是 JLS 15.21.3 告诉你的行为:

At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

这一行:

System.out.println(first.get(i) == second.get(i));

不进行拆箱

==运算符的两边都是Object个实例;因此,将执行的是对象引用相等。

第一种情况 10,仅适用于 "by luck"。

基本上,当您:

first.put(1, 10);

真正叫什么,因为拳击,是:

first.put(Integer.valueOf(1), Integer.valueOf(10));

现在,碰巧 Integer class 有一个内联缓存,它涵盖了从 -128 到 127 至少 的所有值,因为javadoc of Integer.valueOf() 说明:

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

但是155大于127;这意味着不需要此方法来缓存它,在这种情况下将创建一个 new Integer 实例。这就是这里发生的事情。