Arne
Arne

Reputation: 20137

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?

Upvotes: 2

Views: 101

Answers (4)

Elliott Frisch
Elliott Frisch

Reputation: 201439

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.

Upvotes: 1

dkatzel
dkatzel

Reputation: 31648

You can use AtomicInteger which has increment and decrement functions.

if(tmp.containsKey(key))
    tmp.get(key).incrementAndGet();

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213223

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

Upvotes: 6

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

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.

Upvotes: 4

Related Questions