Collections.emptyMap() vs new HashMap()

前端 未结 9 622
南旧
南旧 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:15

    For one, you can get away with reference sharing. A new HashMap() etc will require an allocated object, and possibly some extra elements to hold the data, but you only need one copy of an immutable empty collection (list, set, map, or any other such). This makes it an obvious choice when a method you're calling needs to accept a Map but does not need to edit it.

    I suggest checking out Josh Bloch's Effective Java, which lists some very nice attributes of immutable objects (including thread safety).

提交回复
热议问题