1. Overview
1.概述
In this brief tutorial, we’ll look at ways to check if a key exists in a Map.
在这个简短的教程中,我们将看看如何检查一个键是否存在于Map中。
Specifically, we’ll focus on containsKey and get.
具体来说,我们将关注containsKey 和get。
2. containsKey
2.containsKey
If we take a look at the JavaDoc for Map#containsKey:
如果我们看一下Map#containsKey的JavaDoc。
Returns true if this map contains a mapping for the specified key
如果这个地图包含一个指定键的映射,则返回true。
We can see that this method is a pretty good candidate for doing what we want.
我们可以看到,这个方法是一个相当好的候选者,可以做我们想要的事情。
Let’s create a very simple map and verify its contents with containsKey:
让我们创建一个非常简单的地图,并用containsKey来验证其内容。
@Test
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
Map<String, String> map = Collections.singletonMap("key", "value");
assertTrue(map.containsKey("key"));
assertFalse(map.containsKey("missing"));
}
Simply put, containsKey tells us whether the map contains that key.
简单地说,containsKey 告诉我们地图是否包含该键。
3. get
3.获得
Now, get can sometimes work, too, but it comes with some baggage, depending on whether or not the Map implementation supports null values.
现在,get有时也可以工作,但它有一些包袱,取决于Map的实现是否支持空值。
Again, taking a look at Map‘s JavaDoc, this time for Map#put, we see that it will only throw a NullPointerException:
再来看看Map的JavaDoc,这次是Map#put,我们看到,它只会抛出一个NullPointerException。
if the specified key or value is null and this map does not permit null keys or values
如果指定的键或值是空的而这个地图不允许空键或值。
Since some implementations of Map can have null values (like HashMap), it’s possible for get to return null even though the key is present.
由于Map的某些实现可以有空值(比如HashMap),所以即使键存在,get也可能返回null。
So, if our goal is to see whether or not a key has a value, then get will work:
因此,如果我们的目标是查看一个键是否有一个值,那么get就可以工作:。
@Test
public void whenKeyHasNullValue_thenGetStillWorks() {
Map<String, String> map = Collections.singletonMap("nothing", null);
assertTrue(map.containsKey("nothing"));
assertNull(map.get("nothing"));
}
But, if we are just trying to check that the key exists, then we should stick with containsKey.
但是,如果我们只是想检查键是否存在,那么我们应该坚持使用containsKey。
4. Conclusion
4.结论
In this article, we looked at containsKey. We also took a closer look at why it’s risky to use get for verifying a key’s existence.
在这篇文章中,我们研究了containsKey。我们还仔细研究了为什么使用get来验证一个密钥的存在是有风险的。
As always, check out the code examples over on Github.