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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With