理解HashMap< K,V> [英] Understanding HashMap<K,V>

查看:91
本文介绍了理解HashMap< K,V>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这是我不明白的地方。

如果您尝试使用 get()方法检索对象并返回null时,仍可能将 null 存储为与您提供给 get()方法。您可以通过将对象的密钥传递给map的 containsKey()方法来确定是否是这种情况。如果key存储在map中,这返回 true

那么, containsKey()应该告诉我与提供的键相关联的值是否为 null

这是参考资料,如果你想检查。

Ok, here is the bit I do not understand.
If you attempt to retrieve an object using the get() method and null is returned, it is still possible that null may be stored as the object associated with the key you supplied to the get() method. You can determine if this is the case by passing your key of the object to containsKey() method for map. This returns true if key is stored in the map
So, how is containsKey() supposed to tell me if the value associated with the key supplied is null?
This is the reference if you wanna check. Page 553

推荐答案

考虑以下简单的代码片段:

Consider this simple snippet of code:

Map<String, String> m = new HashMap<String, String>();
m.put("key1", "value1");
m.put("key2", null);

System.out.println("m.get(\"key1\")=" + m.get("key1"));
System.out.println("m.containsKey(\"key1\")=" + m.containsKey("key1"));

System.out.println("m.get(\"key2\")=" + m.get("key2"));
System.out.println("m.containsKey(\"key2\")=" + m.containsKey("key2"));

System.out.println("m.get(\"key3\")=" + m.get("key3"));
System.out.println("m.containsKey(\"key3\")=" + m.containsKey("key3"));

正如您所看到的,我在地图中放入了两个值,其中一个为空。我问了地图三个值:其中两个存在(一个为空),一个不存在。看看结果:

As you can see I put in the map two values, one of which is null. Thene i asked the map for three values: two of them are present (one is null), one is not. Look at the result:

m.get("key1")=value1
m.containsKey("key1")=true
m.get("key2")=null
m.containsKey("key2")=true
m.get("key3")=null
m.containsKey("key3")=false

第二个和第三个是棘手的部分。 key2 存在空值,所以使用 get()不能区分元素是否不在地图中或在 null 值的映射中。但是,使用 containsKey(),您可以返回一个布尔值

The second and the third are the tricky part. key2 is present with null value so, using get() you cannot discriminate whether the element is not in the map or is in the map with a null value. But, using containsKey() you can, as it returns a boolean.

这篇关于理解HashMap&lt; K,V&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆