Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Map.keySet return null

I'm reading some code which checks if the value returned by Map.keySet is null. The javadoc doesn't say anything about the return value of Map.keySet. It's an empty set if the Map doesn't contain anything.

When can the value returned by Map.keySet be null?

like image 240
saga Avatar asked Oct 27 '25 09:10

saga


2 Answers

It's definitely a lack of understanding of Map.keySet from the author of the code you're referring to. As you've mentioned the java doc clearly doesn't state that the keySet method will ever return null.

As an example, i've just looked at the HashMap implementation of the keySet method, it's defined as:

public Set<K> keySet() {
      Set<K> ks = keySet;
      if (ks == null) {
          ks = new KeySet();
          keySet = ks;
      }
      return ks;
}

So, as you can see the value returned from the method is never null.

I've also checked several other implementations of the keySet method e.g. for TreeMap, ConcurrentHashMap et al but couldn't find any that would return null.

like image 98
Ousmane D. Avatar answered Oct 28 '25 22:10

Ousmane D.


Map.keySet should never return null. It is implicit in the documentation that keySet must never be null, because its content "tracks" the content of the Map:

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

This would be impossible to achieve if keySet was allowed to return null.

Standard implementations of the Map in Java, HashMap and TreeMap, do not return null from keySet. Since Map is an interface, one could develop an incorrect implementation of it that returned null for keySet. Programming for this remote possibility would not be a good idea, though.

like image 38
Sergey Kalinichenko Avatar answered Oct 28 '25 22:10

Sergey Kalinichenko