请参见以下代码段。
Integer xInteger = new Integer(1);
map.put('c', xInteger);
xInteger++;
System.out.println(xInteger); // 2
System.out.println(map.get('c')); // 1
System.out.println(xInteger == map.get('c')); // false
我知道HashMap使用Node数组存储K,V对象。但是在这里,哈希表似乎只存储Integer的原始值?因为从HashMap检索的值对象甚至不是我们之前放置的对象。有谁知道hashmap如何处理包装类?
Primitives, primitive wrapper objects, and a number of other types (e.g.
java.lang.String
) are immutable. Their internal state cannot be changed.The only way to update the value of an
Integer
in a map, is to assign a newInteger
to the map entry:As of Java 1.5, Java performs auto-unboxing to convert "wrapper types" such as Integer to the corresponding primitive type
int
when necessary. Then the increment operator can work on the resultingint
.When you do
xInteger++
, it performs that on the primitiveint
. Since primitiveint
is immutable (so is it's wrapper), it is not reflected when you doSystem.out.println(map.get('c'))
.您可以直接写: