Is using java Map.containsKey() redundant when using map.get()
Some Map implementations are allowed to have null values, eg HashMap, in this case if get(key)
returns null
it does not guarantee that there is no entry in the map associated with this key.
So if you want to know if a map contains a key use Map.containsKey
. If you simply need a value mapped to a key use Map.get(key)
. If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; In such case Map.containsKey
is useless and will affect performance. Moreover, in case of concurrent access to a map (eg ConcurrentHashMap
), after you tested Map.containsKey(key)
there is a chance that the entry will be removed by another thread before you call Map.get(key)
.
I think it is fairly standard to write:
Object value = map.get(key);
if (value != null) {
//do something with value
}
instead of
if (map.containsKey(key)) {
Object value = map.get(key);
//do something with value
}
It is not less readable and slightly more efficient so I don't see any reasons not to do it. Obviously if your map can contain null, the two options don't have the same semantics.