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

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

提交回复
热议问题