Why does Map.of not allow null keys and values?

前端 未结 8 1465
清酒与你
清酒与你 2021-01-31 06:37

With Java 9, new factory methods have been introduced for the List, Set and Map interfaces. These methods allow quickly instantiating a Ma

8条回答
  •  甜味超标
    2021-01-31 07:25

    Allowing nulls in maps has been an error. We can see it now, but I guess it wasn't clear when HashMap was introduced. NullpointerException is the most common bug seen in production code.

    I would say that the JDK goes in the direction of helping developers fight the NPE plague. Some examples:

    • Introduction of Optional
    • Collectors.toMap(keyMapper, valueMapper) doesn't allow neither the keyMapper nor the valueMapper function to return a null value
    • Stream.findFirst() and Stream.findAny() throw NPE if the value found is null

    So, I think that disallowing null in the new JDK9 immutable collections (and maps) goes in the same direction.

提交回复
热议问题