一个关于Java中HashMap的remove和size的陷阱?

huangapple go评论77阅读模式
英文:

A trap of remove and size of hashmap in Java?

问题

根据代码显示:
我不理解为什么在第一个映射中,大小是100(在remove()之后),但在第二个映射中,大小是1而不是2。这是因为哈希映射中存储的数据类型之间的差异吗?

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());
    }
}

帮助我!

英文:

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&lt;Short, String&gt; map = new HashMap&lt;Short, String&gt;();
        for (short i = 0; i &lt; 100; i++) {
            map.put(i, String.valueOf(i));
            map.remove(i - 1);
        }

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

    }
}

Help me!

答案1

得分: 8

i-1 是一个 int 表达式,即使 i 是一个 short

这意味着实际上你在调用 map.remove(Integer.valueOf(i - 1))

一个 Integer 对象永远不会等于一个 Short 对象,即使它们有相同的值,所以 remove 调用会失败(即不会移除任何内容)。

相反,你应该写成 map.remove((short) (i-1));

为什么 map.remove() 甚至接受不是键类型的对象是 一个不同的问题

英文:

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.

huangapple
  • 本文由 发表于 2020年10月6日 19:45:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64225144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定