Collections.emptyMap() vs new HashMap()

From Effective JavaItem #43 – "Return empty arrays or collections, not null" demonstrates returning an empty collection and perhaps even demonstrates using these emptyList()emptySet(), and emptyMap() methods on the Collections class to get an empty collection that also has the additional benefit of being immutable. From Item #15 "Minimize Mutability".

From Collections-emptySet-Collections-emptyList-Collections

Its a type of programming idiom. This is for people that do not want null variables. So before the set gets initialized, they can use the empty set.

Note: Below code is just an example (change it according to your use case):

private Set myset = Collections.emptySet();

void initSet() {
   myset = new HashSet();
}
void deleteSet() {
   myset = Collections.emptySet();
}

These methods offer a couple of advantages:

  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.

Leave a Comment