Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment an Integer-lvalue

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?

like image 405
Arne Avatar asked Dec 12 '25 23:12

Arne


2 Answers

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();
like image 190
Rohit Jain Avatar answered Dec 15 '25 13:12

Rohit Jain


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.

like image 23
Sotirios Delimanolis Avatar answered Dec 15 '25 11:12

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!