Erik Madsen Erik Madsen - 2 years ago 112
Java Question

Is using java Map.containsKey() redundant when using map.get()

I have been wondering for some time whether it is allowable within best practice to refrain from using the

method on
and instead do a null check on the result from

My rationale is that it seems redundant to do the lookup of the value twice - first for the
and then again for

On the other hand it may be that most standard implementations of
cache the last lookup or that the compiler can otherwise do away with the redundancy, and that for readability of the code it is preferable to maintain the

I would much appreciate your comments.

Answer Source

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). Map.containsKey will be useless and will affect performance. Moreover, in case of concurrent access to a map (eg ConcurrentHashMap), after you tested Map.containsKey(key) there is chance that the entry will removed by another thread before you call Map.get(key).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download