1

As the code shows: I don't understand why in the first map, the size is 100(after remove()), but in the second map, the size is 1 instead of 2. Is that because of the difference between data type stored in hashmap or?


public class test {
    public static void main(String[] args) {
        Map<Short, String> map = new HashMap<Short, String>();
        for (short i = 0; i < 100; i++) {
            map.put(i, String.valueOf(i));
            map.remove(i - 1);
        }

        Map<Integer, Integer> hashmap = new HashMap<>();
        hashmap.put(3,4);
        hashmap.put(4,5);
        hashmap.remove(3);
        System.out.println(hashmap.size());
        System.out.println(map.size());

    }
}

Help me!

  • 1
    As a general suggestion I'd say that there are exceedingly few good reasons to even use `short` or `Short` in Java. Outside of `short[]` there are almost no benefits for using those type. Just use `int` / `Integer`. – Joachim Sauer Oct 06 '20 at 11:56

1 Answers1

8

i-1 is an int expression, even if i is a short.

That means you effectively call map.remove(Integer.valueOf(i - 1)).

An Integer object is never equal to a Short object, even if they have the same value, so the remove call will fail (i.e. not remove anything).

Instead you should write map.remove((short) (i-1));.

Why map.remove() even accepts objects that are not of the type of the key is a different question.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614