The containsKey(Object key) method on a Map need only be used when it is not intended to try and retrieve a value from the map.  If key is not in the collection, a get call will return null anyway.

:
if (mobileRenderingProfiles.containsKey(userAgent))
{
    profile = mobileRenderingProfiles.get(userAgent);
}
:

In the above example, the mobileRenderingProfiles map is massive, so the containsKey( ) call may take a non-trivial amount of time to find the data it seeks.

Yet, it is followed almost immediately by a get( ) call, which will do an almost identical search to find the same item in the map.

A better way would be as below.  

MobileRenderingProfile profile = mobileRenderingProfiles.get(userAgent);
if (profile != null)
{
    :
}

Thus an additional lookup in the map is saved and the code is a little simpler.

blog comments powered by Disqus