Question

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?

Was it helpful?

Solution

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();

OTHER TIPS

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.

Sorry, but not with an Integer wrapper class. Wrapper objects are immutable, so you're actually getting a new reference there. Consider this code,

Integer i = 1;
Integer j = i;
System.out.printf("i=%d, j=%d, i == j is %b\n", i, j, i == j);
++i;
System.out.printf("i=%d, j=%d, i == j is %b\n", i, j, i == j);

You will notice that the increment of i has no effect on j.

You can use AtomicInteger which has increment and decrement functions.

if(tmp.containsKey(key))
    tmp.get(key).incrementAndGet();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top