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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:41:47  来源:igfitidea点击:

Is Map.containsKey() useful?

javamap

提问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 nullvalues:

是 - 键可以有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 nullvalue from a non-existent entry was a pretty bad design decision when they first made Java's collection API.

你可能会争辩说(我同意),null当他们第一次制作 Java 的集合 API 时,不区分值和不存在的条目是一个非常糟糕的设计决定。

(Some maps - Hashtableand ConcurrentHashMap, at least - don't allow nullvalues, which makes containsKeyless 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 nullvalues, with just get(key)you can't differentiate between key/value pair that has value = nulland "no matching key/value pair exists".

如果您的地图允许null值,只是get(key)您无法区分具有 value = 的null键/值对和“不存在匹配的键/值对”。

回答by Marco Forberg

Yes it is useful - especially if your Map allows nullvalues...

是的,它很有用 - 特别是如果您的地图允许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"));
}