java – Map. Is containskey () useful?

See English answer > is using java map containsKey() redundant when using map. Get() 6

Map myMap ....
if myMap.containsKey(key) {
   Object value = myMap.get(key);
   .....
}

Examples of not using containskey:

Object value = myMap.get(key);
if (value != null) {
 ......
}

Edit: clarify empty keys and values Assuming that the mapping does not allow null keys and null values, the two examples are the same

Solution

Yes – the key can have a null value:

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 can argue (and I agree) that when they first created Java's collection API, it was a very bad design decision not to distinguish between null values and non-existent entries

(some maps - at least hashtable and concurrenthashmap - do not allow null values, which makes containskey less important, but it still improves readability than m.get (k) = = null.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>