Collections.emptyMap() vs new HashMap()

前端 未结 9 599
南旧
南旧 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条回答
  •  萌比男神i
    2020-12-22 22:12

    Most of the time we use a constructor to create a new empty map. But the Collections methods offer a couple of advantages to create an empty map using static method java.util.Collections.emptyMap()

    1. They're more concise because you don't need to explicitly type out the generic type of the collection - it's generally just inferred from the context of the method call.

    2. They're more efficient because they don't bother creating new objects; they just re-use an existing empty and immutable object. This effect is generally very minor, but it's occasionally (well, rarely) important.

提交回复
热议问题