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 thekeySet
method will ever returnnull
.As an example, i've just looked at the
HashMap
implementation of thekeySet
method, it's defined as: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. forTreeMap
,ConcurrentHashMap
et al but couldn't find any that would return null.Map.keySet
should never returnnull
. It is implicit in the documentation thatkeySet
must never benull
, because its content "tracks" the content of theMap
:This would be impossible to achieve if
keySet
was allowed to returnnull
.Standard implementations of the
Map
in Java,HashMap
andTreeMap
, do not returnnull
fromkeySet
. SinceMap
is an interface, one could develop an incorrect implementation of it that returnednull
forkeySet
. Programming for this remote possibility would not be a good idea, though.