Using ++ Unary Operator with a Map Get function in Java

702 views Asked by At

If an Integer value from within a Map is going to be extracted and placed into a new int variable with one added to it why does the ++ operator not work with the map.get() function? e.g., int foo = map.get(key)++;

To get around this I used

  HashMap<key, Integer> map = new HashMap<key, Integer>();

  //Integer values are added in

  int foo = map.get(key);
  foo++;

But I am curious as to why the prior example is an invalid argument. According to documentation the Map get() function returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Granted the value returned is not null, an Integer will be returned, so shouldn't that Integer be able to be incremented before going into foo?

2

There are 2 answers

0
Seelenvirtuose On BEST ANSWER

Look at JLS ยง15.14.2:

A postfix expression followed by a ++ operator is a postfix increment expression.

PostIncrementExpression:
  PostfixExpression ++ 

The result of the postfix expression must be a variable [...]

This clearly defines the syntax of the postfix increment expression, and also clearly states that the postfix expression must be a variable.

Thus, you simply cannot use the operator ++ onto a method call.

3
Lalit Mehra On

increment/decrement operators work only on variables and not on literal numeric values

    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(1, 1);

     // These will work
     int foo = map.get(1);
     System.out.println(foo);
     foo++;
     System.out.println(foo);

     // This will not work because of the reason mentioned above
     System.out.println(map.get(1) ++);