Why doesn't the last line of following code compile in Java?
HashMap<String, Integer> map = new HashMap();
map.put("a", 1);
map.get("a") += 1;
Something like that works fine for C++.
Why doesn't the last line of following code compile in Java?
HashMap<String, Integer> map = new HashMap();
map.put("a", 1);
map.get("a") += 1;
Something like that works fine for C++.
You are trying to change the map value by using the get method. In your code, the map.get("a"); will only RETURN a Integer. You cannot change the value of the Integer stored inside the HashMap object without using the setter method .put()
Something like this is acceptable:
map.put("a",1);
map.put("a",map.get("a") + 1);
However, this:
map.get("a") += 1;
Is not acceptable and will not compile, because you cannot change the value of the object through a getter method.
The reason why getter and setter methods, like map.put() & map.get(), are so important in Java can be found here
Something like that works fine for C++.
Java is not C++ so you should not expect that something that is valid in C++ is equally valid in Java.
If you want to update the value stored under a certain key in a map, you'll have to put it in the map again with the new value, which will replace the old value. For example:
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
// Get the value stored under "a", add one and store the new value
map.put("a", map.get("a") + 1);
What you get as a result from the map.get is an Integer object. And those Integer objects do not support the += operator (as you know them from C++) as you cannot overload operators in Java generally.
Instead you have to put it into the map again using the map.put function.
Notice that an Integer object is different from an built-in int type!