Search code examples
javadictionaryhashmapunary-operator

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


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?


Solution

  • 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.