Collections.emptyMap() vs new HashMap()

From Effective Java, Item #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.


It is, in my personal experience admittedly, very useful in cases where an API requires a collection of parameters, but you have nothing to provide. For example you may have an API that looks something like this, and does not allow null references:

public ResultSet executeQuery(String query, Map<String, Object> queryParameters);

If you have a query that doesn't take any parameters, it's certainly a bit wasteful to create a HashMap, which involves allocating an array, when you could just pass in the 'Empty Map' which is effectively a constant, the way it's implemented in java.util.Collections.