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

前端 未结 8 1556
清酒与你
清酒与你 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:31

    The documentation does not say why null is not allowed:

    They disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException.

    In my opinion, the Map.of() and Map.ofEntries() static factory methods, which are going to produce a constant, are mostly formed by a developer at the compile type. Then, what is the reason to keep a null as the key or the value?

    Whereas, the Map#put is usually used by filling a map at runtime where null keys/values could occur.

提交回复
热议问题