I have a map from type
Map<Character, Integer> tmp;
and at some point in my code, I do the following:
if(tmp.containsKey(key))
tmp.put(key, tmp.get(key)+1)
In the second line, I would prefer to just do something like
tmp.get(key)++;
which I expected to work, since I should get a reference to the Integer Object from the get-call. But it doesn't, and Integer doesn't seem to have an update function apart from the int-syntax. Is there no way around the first construct?
Since Integer class objects are immutable, you can't modify it. You've to put the result back into the map. One option is to use mutable value like AtomicInteger:
Map<Character, AtomicInteger> tmp;
tmp.get(ch).incrementAndGet();
Primitives don't work with generics, so you have to use Integer objects instead of int values.
You can't use this
tmp.get(key)++;
because that gets translated into something like
Integer value = tmp.get(key);
int intValue = value.intValue();
value = Integer.valueOf(intValue += 1); // different Integer reference now stored in value
So you see, the reference in tmp remains the same.
The way you are currently doing it is correct. Or do what Rohit is suggesting with a class that wraps the increment operation, like AtomicInteger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With