Because i++
returns i
before incrementing i
. See my comments:
Map<String, Integer> a = new HashMap<>();
a.put("x", new Integer(0)); // x=0
Integer i = a.get("x"); // i=0
a.put("x", i++); // x=0, i=1
i = a.get("x"); // i=0
a.put("x", i++); // x=0, i=1
i = a.get("x"); // i=0
a.put("x", i++); // x=0, i=1
System.err.println(i);
Here's the relevant part from the documentation of unary operators:
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++;
and ++result;
will both end in result being incremented by one.
The only difference is that the prefix version (++result
) evaluates to the incremented value, whereas the postfix version (result++
) evaluates to the original value.
If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.