NimChimpsky NimChimpsky - 1 month ago 7
Java Question

Increment an Integer within a HashMap

Do I have to return the object and then put a new one in ? Or can I just directly increment ?

Integer temp = myMap.get(key);
temp++;
myMap.put(key, temp);


there is no way to just do this (this doesn't work) :

myMap.get(key)++;

Answer

Do I have to return the object and then put a new one in ?

As long as you use the Integer wrapper class yes, because it's immutable. You could use a mutable wrapper class instead, even one that has an increment() method. However, you then lose the ability to use autoboxing and autounboxing on the values.