[英]Understanding HashMap<K,V>
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. 如果尝试使用
get()
方法检索对象并返回null,则仍可能将null
存储为与提供给get()
方法的键关联的对象。 You can determine if this is the case by passing your key of the object to containsKey()
method for map. 您可以通过将对象的键传递给map的
containsKey()
方法来确定是否是这种情况。 This returns true
if key is stored in the map 如果键存储在地图中,则返回
true
So, how is containsKey()
supposed to tell me if the value associated with the key supplied is null
? 那么,
containsKey()
应该如何告诉我与提供的密钥相关的值是否为null
?
This is the reference if you wanna check. 如果你想检查,这是参考 。 Page 553
第553页
Map<String, Object> map = new HashMap<String, Object>();
map.put("Foo", null);
System.out.println(map.containsKey("Foo"));
System.out.println(map.containsKey("Boo"));
OUTPUT: OUTPUT:
true
false
get()
returns null
in two cases: get()
在两种情况下返回null
:
null
. null
。 You can't tell from get()
which is true. 你不能告诉
get()
这是真的。 However, containsKey()
will tell you if the key was present in the map, regardless of whether its associated value was null
. 但是,
containsKey()
将告诉您密钥是否存在于映射中,无论其关联值是否为null
。
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. 如您所见,我在地图中放入了两个值,其中一个值为null。 Thene i asked the map for three values: two of them are present (one is null), one is not.
Thene我向地图询问了三个值:其中两个存在(一个为空),一个不存在。 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
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. key2
以null值存在,因此,使用get()
您无法区分元素是否不在地图中,或者是否在地图中具有null
值。 But, using containsKey()
you can, as it returns a boolean
. 但是,使用
containsKey()
可以,因为它返回一个boolean
。
(get() == null && containsKey()) == value is null
containsKey would tell you if the key is in the hashmap at all. containsKey会告诉你密钥是否在hashmap中。 Consider the case where a key is present with null value and the other case in which the key which you are looking for is not at all in the hashmap.
考虑一个键存在空值的情况和另一种情况,其中您要查找的键在hashmap中根本不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.