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?

1
  • 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. Commented Aug 6, 2017 at 11:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Then how this works : Integer h = new Integer(1); System.out.println(h); h++; System.out.println(h); the output is 1 2
@luk2302 It is explained here.
@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).
@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.
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!

1 Comment

Then how this works : Integer h = new Integer(1); System.out.println(h); h++; System.out.println(h); the output is 1 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.