What is the use of adding a null key or value to a HashMap in Java?

前端 未结 7 1407
挽巷
挽巷 2020-12-12 16:19

HashMap allows one null key and any number of null values. What is the use of it?

相关标签:
7条回答
  • 2020-12-12 16:29

    The answers so far only consider the worth of have a null key, but the question also asks about any number of null values.

    The benefit of storing the value null against a key in a HashMap is the same as in databases, etc - you can record a distinction between having a value that is empty (e.g. string ""), and not having a value at all (null).

    0 讨论(0)
  • 2020-12-12 16:32

    One example would be for modeling trees. If you are using a HashMap to represent a tree structure, where the key is the parent and the value is list of children, then the values for the null key would be the root nodes.

    0 讨论(0)
  • 2020-12-12 16:35

    I'm not positive what you're asking, but if you're looking for an example of when one would want to use a null key, I use them often in maps to represent the default case (i.e. the value that should be used if a given key isn't present):

    Map<A, B> foo;
    A search;
    B val = foo.containsKey(search) ? foo.get(search) : foo.get(null);
    

    HashMap handles null keys specially (since it can't call .hashCode() on a null object), but null values aren't anything special, they're stored in the map like anything else

    0 讨论(0)
  • 2020-12-12 16:43

    A null key can also be helpful when the map stores data for UI selections where the map key represents a bean field.

    A corresponding null field value would for example be represented as "(please select)" in the UI selection.

    0 讨论(0)
  • 2020-12-12 16:44

    One example of usage for null values is when using a HashMap as a cache for results of an expensive operation (such as a call to an external web service) which may return null.

    Putting a null value in the map then allows you to distinguish between the case where the operation has not been performed for a given key (cache.containsKey(someKey) returns false), and where the operation has been performed but returned a null value (cache.containsKey(someKey) returns true, cache.get(someKey) returns null).

    Without null values, you would have to either put some special value in the cache to indicate a null response, or simply not cache that response at all and perform the operation every time.

    0 讨论(0)
  • 2020-12-12 16:51

    Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"

    0 讨论(0)
提交回复
热议问题