Integer xInteger = new Integer(1);
map.put('c', xInteger);
System.out.println(xInteger);  // 2
System.out.println(map.get('c')); // 1
System.out.println(xInteger == map.get('c')); // false


  • 夏子洛
    夏子洛 回复

    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