在 hashmap 中允许多个 null 键有什么好处?
为了进行实验,我在 Hashmap
实例中添加了多个 null
键。它没有抱怨。这样做有什么好处呢?
代码是:
Map hmap = new HashMap();
hmap.put("sushil","sushil11" );
hmap.put(null,null);
hmap.put(null,"king");
hmap.put(null,"nagasaki");
hmap.put(null,null);
地图上有多少个钥匙?
Just for experimenting, I added multiple null
keys in a Hashmap
instance. And it didn't complain. What's the benefit of doing that?
The code is,
Map hmap = new HashMap();
hmap.put("sushil","sushil11" );
hmap.put(null,null);
hmap.put(null,"king");
hmap.put(null,"nagasaki");
hmap.put(null,null);
How many keys are there in the map?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这个问题询问了 HashMap 中是否有多个键,这是不可能的。
如果一次又一次传递 null,则仅替换旧值。
请参阅:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java#HashMap.putForNullKey %28java.lang.Object%29
The question has asked about having multiple keys in HashMap which is not possible.
If you pass null again and again the old value is replaced only.
Refer:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java#HashMap.putForNullKey%28java.lang.Object%29
HashMap允许多个空值,但只允许一个空键。
如果您像下面这样编写多个 null 键,那么 null 将被覆盖,您将得到最终的覆盖结果。即“世界”
输出:
HashMap allows multiple null values but only one null key.
If you write multiple null keys like below, then null will be overrides and you'll get the final overridden result. i.e "world"
Output:
我猜你还没有添加多个
null
键。您只是多次覆盖同一个null
键。I would guess you haven't added multiple
null
-keys. You just overwrote the samenull
key multiple times.普通的哈希映射将具有唯一的键,因此您将重复覆盖空键的条目。您不会有多个相同的键(为此您需要 MultiMap 或类似的)
A normal hashmap will have unique keys, so you're overwriting the entry for the null key repeatedly. You won't have multiple identical keys (for this you need a MultiMap or similar)
它用于获取 switch:case:default 行为。
示例:
问题定义:计算机科学系大楼内的咖啡店。他们为 CS 学生提供咖啡,价格为 1.00 美元,为 IT 系学生提供咖啡 1.25 美元,其他学生提供咖啡为 1.50 美元。
那么Map将会是:
Key ->价值
IT -> 1.25
CS-> 1.00
空 -> 1.50
PS - 如果这是一个词的话,我不是“部门主义者”。 :)
It is used to get switch:case:default behavior.
Example:
Problem Definition: Coffee shop in CS Department building. They provide coffee to CS Student for $1.00, to IT department students $1.25 and others for $1.50.
Then Map will be:
Key -> Value
IT -> 1.25
CS -> 1.00
null -> 1.50
P.S. - I am not "Department-ist" if that's a word. :)
有一个 API 调用:
大小:返回此映射中键值映射的数量。
如前所述,您只是用新值覆盖键/值对。
There's an API call for this:
size: Returns the number of key-value mappings in this map.
As noted you're just overwriting the key/value pair with a new value.