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

前端 未结 7 1411
挽巷
挽巷 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: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 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

提交回复
热议问题