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

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

    Exactly - a HashMap is allowed to store null, not the Map returned by the static factory methods. Not all maps are the same.

    Generally as far as I know it has a mistake in the first place to allow nulls in the HashMap as keys, newer collections ban that possibility to start with.

    Think of the case when you have an Entry in your HashMap that has a certain key and value == null. You do get, it returns null. What does the mean? It has a mapping of null or it is not present?

    Same goes for a Key - hashcode from such a null key has to treated specially all the time. Banning nulls to start with - make this easier.

提交回复
热议问题