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

前端 未结 8 1463
清酒与你
清酒与你 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条回答
  •  Happy的楠姐
    2021-01-31 07:34

    Not all Maps allow null as key

    The reason mentioned in the docs of Map.

    Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException.

提交回复
热议问题