Difference Between Math Operations and Function Calls with Map.get()

Viewed 17

Why am I not able to do:

Map<String, Integer> myMap =  new HashMap<>();
        String[] words = "the fox, the quick brown fox jumps".split(" ");
        for(String word : words) {
            myMap.putIfAbsent(word, 0);
            myMap.get(word)++;
        }
        System.out.println(myMap);

but I can do:

Map<Character, List<String>> myMap =  new HashMap<>();
        String[] words = "the fox, the quick brown fox jumps".split(" ");
        for(String word : words) {
            char firstLetter = word.charAt(0);
            myMap.putIfAbsent(firstLetter, new ArrayList<String>());
            myMap.get(firstLetter).add(word);
        }
        System.out.println(myMap);

What is the technical difference that makes me able to change a value in the second case, but not in the first? Please let me know how I can make my question more clear if it is not already!

1 Answers

The ++ unary operator expects the name of variable, not an arbitrary expression. var++ is semantically equivalent to var = var + 1. How would that look in your case?

myMap.get(word) = myMap.get(word) + 1

This is not a valid assignment, which is why it's a compilation error to attempt it.

Java's type system knows nothing about Maps or any collection, so it's not even possible for it to do anything smarter like automatically convert this into some mutation of the map.

Related