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

In the following code snippet:

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

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

The same question is about getting values, is it useful to check for availability first if you know that the map does not contain null values?

 if (map.containsKey(key)) { Object value = map.get(key); } 
+5
source share
4 answers

remove returns null if there is no mapping for key exception will not be thrown:

 public V remove(Object key) 

I see no reason to do this if before trying to remove the key , perhaps perhaps if you want to count the number of elements deleted from the map.

In the second example, you will get null if key does not exist. Regardless of whether or not to check, depends on your logic.

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

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

+4
source

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

No, this is counterproductive:

  • In case the item is missing, you will not see the difference
  • In case the item is there, you will get two kinds of search.

If you want to correctly delete an element, just call map.remove(key) .

The same question is about getting values

The same logic applies here. Of course, you need to check the result for null , so in this case if will stay there.

Note that this cleaning exercise begins with readability, and only then about performance. Access to the card is a quick operation, so accessing it twice is unlikely to cause serious performance problems, except in some fairly extreme cases. However, removing additional conditional code will make your code more readable, which is very important.

+3
source

The Java documentation on remove() states that it will remove an element only if the card contains such an element. Thus, checking contains() before remove() is redundant.

0
source

This is subjective (and completely the case of style), but for the case when you retrieve the value, I prefer the call to contains(key) for a null check. Boolean comparisons just feel better than zero comparisons. I would probably feel different if Map<K,V>.get(key) returned Optional<V> .

In addition, it is worth noting that β€œgiven null keys” is a statement that can be quite difficult to prove, depending on the type of Card (which you don’t even know). In general, I think that redundant search checking (or maybe just feeling) is safer, in case something happens there (knocks on a tree, checks black cats and avoids the exit stairs).

For the delete operation, you are in place. Verification is useless.

0
source

Source: https://habr.com/ru/post/1213044/


All Articles