1

I was trying sample code and some got result which I don't understand:

 Map<Integer,Integer> map = new HashMap<>();
 map.put(1, 2);
 System.out.println(map.get(1));
 Integer k = map.get(1);
 k++;
 System.out.println(map.get(1));

The result:

2
2

But as Integer is an object, the change should get reflected in the map value as well? So why is the value not changing?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 1
    your understanding is wrong. `Integer` (and all other boxed types) is immutable. `k++` returns a new Integer with the value 3, the original Integer stays 2. – luk2302 Aug 06 '17 at 11:18

2 Answers2

3

Integer is immutable, and k++ doesn't change the value of the Integer stored in the Map. It create a new Integer instance.

You should put the new value in the Map in order for the Map to be modified:

     Map<Integer,Integer> map = new HashMap<>();
     map.put(1, 2);
     System.out.println(map.get(1));
     Integer k = map.get(1);
     k++;
     map.put(1, k);
     System.out.println(map.get(1));

If Integer was a mutable class, and you would have called a method that mutates its state, you wouldn't have needed to put the value again in the Map.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Then how this works : Integer h = new Integer(1); System.out.println(h); h++; System.out.println(h); the output is 1 2 – Java Beginner Aug 06 '17 at 11:22
  • @luk2302 It is explained [here](https://stackoverflow.com/questions/13280134/why-does-post-increment-work-on-wrapper-classes). – Eran Aug 06 '17 at 11:24
  • @JavaBeginner `h++` unboxes the `Integer` to an `int`, increments that `int` and assigns the incremented value back to the `h` variable (which requires boxing the `int` to `Integer`). – Eran Aug 06 '17 at 12:15
  • @JavaBeginner Because `h++` only assigns a new value (new Object) to `h`. It doesn't change the value that was already put in the Map. – Eran Aug 06 '17 at 12:21
1

Misconception on your end: Integer is immutable!

That means that k++ creates a new Integer object. It is impossible to change the value of an existing Integer object!

GhostCat
  • 137,827
  • 25
  • 176
  • 248