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

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

    While HashMap does allow null values, Map.of does not use a HashMap and throws an exception if one is used either as key or value, as documented:

    The Map.of() and Map.ofEntries() static factory methods provide a convenient way to create immutable maps. The Map instances created by these methods have the following characteristics:

    • ...

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

提交回复
热议问题