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

前端 未结 8 1297
清酒与你
清酒与你 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条回答
  •  梦毁少年i
    2021-01-31 07:23

    The major difference is: when you build your own Map the "option 1" way ... then you are implicitly saying: "I want to have full freedom in what I am doing".

    So, when you decide that your map should have a null key or value (maybe for the reasons listed here) then you are free to do so.

    But "option 2" is about a convenience thing - probably intended to be used for constants. And the people behind Java simply decided: "when you use these convenience methods, then the resulting map shall be null-free".

    Allowing for null values means that

     if (map.contains(key)) 
    

    is not the same as

     if (map.get(key) != null)
    

    which might be a problem sometimes. Or more precisely: it is something to remember when dealing with that very map object.

    And just an anecdotal hint why this seems to be a reasonable approach: our team implemented similar convenience methods ourselves. And guess what: without knowing anything about plans about future Java standard methods - our methods do the exact same thing: they return an immutable copy of the incoming data; and they throw up when you provide null elements. We are even so strict that when you pass in empty lists/maps/... we complain as well.

提交回复
热议问题