Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Map.containsKey() useful in a Map that has no null values?

In the following piece of code:

if (map.containsKey(key)) {
    map.remove(key);
}

Looking at performance, is it useful to first do a Map.containsKey() check before trying to remove the value from the map?

Same question goes for retrieving values, is it useful to first do the contains check if you know that the map contains no null values?

if (map.containsKey(key)) {
    Object value = map.get(key);
}
like image 857
Elite_Dragon1337 Avatar asked Feb 10 '15 11:02

Elite_Dragon1337


2 Answers

remove returns null if there's no mapping for key no exception will be thrown:

public V remove(Object key)

I don't see any reason to perform that if before trying to remove a key, perhaps maybe if you want to count how many items where removed from the map..

In the second example, you'll get null if the key doesn't exist. Whether to check or not, depends on your logic.

Try not to waste your time on thinking about performance, containsKey has O(1) time complexity:

This implementation provides constant-time performance for the basic operations (get and put)

like image 160
Maroun Avatar answered Oct 24 '22 13:10

Maroun


is it useful to first do a Map.containsKey() check before trying to remove the value from the map?

No, it is counterproductive:

  • In the case when the item is not there, you would see no difference
  • In the case when the item is there, you would end up with two look-ups.

If you want to remove the item unconditionally, simply call map.remove(key).

Same question goes for retrieving values

Same logic applies here. Of course you need to check the result for null, so in this case if stays there.

Note that this cleanup exercise is about readability first, and only then about performance. Accessing a map is a fast operation, so accessing it twice is unlikely to cause major performance issues except for some rather extreme cases. However, removing an extra conditional will make your code more readable, which is very important.

like image 32
Sergey Kalinichenko Avatar answered Oct 24 '22 14:10

Sergey Kalinichenko