When does Map.keySet return null

2019-07-20 18:15发布

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?

2条回答
beautiful°
2楼-- · 2019-07-20 18:57

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-20 18:58

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.

查看更多
登录 后发表回答