Efficiency: HashMap check containsKey() vs always put()

tom :

If I have a HashMap and I want to insert key value pairs with a lot of duplicates, is it better to do: if (!map.containsKey(key)) map.put(key, value); or simply do map.put(key,value); regardless of if the key/value pair already exists?

Debosmit Ray :

If you don't care about the dupes, just do map.put(key, value);. That way, you don't do an extra O(1) lookup (which includes hashing the key and then checking if it exists).

In the worst case, this can save you about n-1 extra lookups for the case where the exact same (key, value) pair is inserted repeatedly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113050&siteId=1