Collections.emptyMap() vs new HashMap()

前端 未结 9 589
南旧
南旧 2020-12-22 21:22

What are some of the situations where I can use Collections.emptyMap() ? The Documentation says I can use this method if I want my collection to be immutable. <

9条回答
  •  情话喂你
    2020-12-22 22:16

    Why would I want an immutable empty collection? What is the point?

    There are two different concepts here that appear strange when viewed together. It makes more sense when you treat the two concepts separately.

    • Firstly, you should prefer to use an immutable collection rather than a mutable one wherever possible. The benefits of immuablity are well documented elsewhere.

    • Secondly, you should prefer to use an empty collection rather than to use null as a sentinel. This is well described here. It means that you will have much cleaner, easier to understand code, with fewer places for bugs to hide.

    So when you have code that requires a map, it is better to pass an empty map rather than a null to indicate the absence of a map. And most of the time when you are using a map, it is better to use an immutable map. So this is why there is a convenience function to make an immutable empty map.

提交回复
热议问题