Java Map.containsKey() 有用吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16398334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is Map.containsKey() useful?
提问by dhblah
I'm wondering, does it make any sense to check for a particular key before trying to access it. Example:
我想知道,在尝试访问特定密钥之前检查它是否有意义。例子:
Map myMap ....
if myMap.containsKey(key) {
Object value = myMap.get(key);
.....
}
Example of not using containsKey
:
不使用的例子containsKey
:
Object value = myMap.get(key);
if (value != null) {
......
}
EDIT: to clarify on null keys and values. Let's say, that map doesn't allow null keys and null values, so this two examples be identical.
编辑:澄清空键和值。假设该映射不允许空键和空值,因此这两个示例是相同的。
采纳答案by gustafc
Yes - keys can have null
values:
是 - 键可以有null
值:
Map myMap = ...;
myMap.put("foo", null);
if (myMap.containsKey("foo")) {
Object value = myMap.get(key); // value is null
}
Object value = myMap.get("foo");
if (value != null) {
// you won't get here
}
You could argue (and I'd agree) that not distinguishing a null
value from a non-existent entry was a pretty bad design decision when they first made Java's collection API.
你可能会争辩说(我同意),null
当他们第一次制作 Java 的集合 API 时,不区分值和不存在的条目是一个非常糟糕的设计决定。
(Some maps - Hashtable
and ConcurrentHashMap
, at least - don't allow null
values, which makes containsKey
less important there, but it's still a nice readability improvement over m.get(k) == null
.)
(一些地图 -Hashtable
并且ConcurrentHashMap
,至少 - 不允许null
值,这在containsKey
那里变得不那么重要,但它仍然是一个很好的可读性改进m.get(k) == null
。)
回答by vertti
In case your map allows for null
values, with just get(key)
you can't differentiate between key/value pair that has value = null
and "no matching key/value pair exists".
如果您的地图允许null
值,只是get(key)
您无法区分具有 value = 的null
键/值对和“不存在匹配的键/值对”。
回答by Marco Forberg
Yes it is useful - especially if your Map allows null
values...
是的,它很有用 - 特别是如果您的地图允许null
值...
@Test
public void testContainsKey() {
Map<String, Object> strObjMap = new HashMap<String, Object>();
strObjMap.put("null", null);
assertTrue(strObjMap.containsKey("null"));
assertNull(strObjMap.get("null"));
}