-2

What's wrong with this? Specifically, what's wrong with intCount.put(i, intCount.get(i)++)?

public static Map<Integer, Integer> countNumbers(List<Integer> list) {
    Map<Integer, Integer> intCount = new TreeMap<>();
    for (Integer i : list) {
      if (intCount.get(i) == null) {
        intCount.put(i, 1);
      } else {
        intCount.put(i, ++intCount.get(i));
      }
    }
    return intCount;
  }

This works, on the other hand

public static Map<Integer, Integer> countNumbers(List<Integer> list) {
    Map<Integer, Integer> intCount = new TreeMap<>();
    for (Integer i : list) {
      if (intCount.get(i) == null) {
        intCount.put(i, 1);
      } else {
        intCount.put(i, intCount.get(i) + 1);
      }
    }
    return intCount;
  }

Does it mean I can't increment Integers, only int primitives? The problem is when I cast Integer into its respective primitive (or rather, an Integer returning method into its respective primitive) like this

intCount.put(i, ++(int)(intCount.get(i)));

it doesn't work either! Why?

Main.java:30: error: unexpected type

intCount.put(i, ++(int)(intCount.get(i)));

^ required: variable

found: value

1 error

  • 1
    In the 1st case, the code tries to increment a value / literal, not a variable. Pre- and postincrement can only be executed on variables, not values / literals. – Turing85 Jan 01 '23 at 16:46
  • 1
    Think of it this way: what would be the semantics of, for example, `1++`? `1` is a literal, there is nothing to "assign the value back to". Or if there were, the literal `1` would now represent the value `2`, which would be confusing as heck. – Turing85 Jan 01 '23 at 16:50

1 Answers1

2

intCount.get(i) gets a value, there is no variable to increment. Regardless, I would remove the if and else entirely and use Map.getOrDefault(Object, V) like

intCount.put(i, intCount.getOrDefault(i, 0) + 1);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249