使用两个不同的HashMap检查相同的Integer值时返回false

时间:2015-04-11 17:42:38

标签: java 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

2 个答案:

答案 0 :(得分:3)

在这一行:

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

不会发生拆箱

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

第一个案例10仅适用于运气&#34;

基本上,当你:

时会发生什么
first.put(1, 10);

因拳击而真正称之为:

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

现在,恰好Integer类有一个内联缓存,涵盖了-128到127 的所有值,至少,正如javadoc of Integer.valueOf()所解释的那样: / p>

  

此方法将始终缓存-128到127(包括端点)范围内的值,并可以缓存此范围之外的其他值。

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

答案 1 :(得分:0)

JLS 15.21.3告诉你的行为是什么:

  

在运行时,如果操作数值都是,则==的结果为真   null或两者都指向同一个对象或数组;否则,结果   是假的。