Java的包装类如何存储在HashMap中?

请参见以下代码段。

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 new Integer to the map entry:

    int i = 1;
    
    map.put('c', i); // will be auto-boxed to Integer
    map.put('c', ++i); // will do i = i + 1, and auto-box the result to Integer
    
  • eipsum
    eipsum 回复

    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 resulting int.

    When you do xInteger++, it performs that on the primitive int. Since primitive int is immutable (so is it's wrapper), it is not reflected when you do System.out.println(map.get('c')).

    您可以直接写:

    Integer xInteger = 1; // no need for boxing