Search code examples
javacollectionseffective-java

Returning empty collections in accordance with Effective Java


Effective Java, Item 43 states:

return unmodifiable empty collections instead of null.

So far so good. Are there any guidelines, exactly what to return? Does this question even make sense? What I am thinking about is:

  • Does it make a difference whether you return an emtpy LinkedList<> or ArrayList<>(0)?
  • Does it make a difference whether you return an empty HashMap<> or TreeMap<>?
  • etc.

Performance difference? Hardly.

Memory footprint? Maybe.

CPU footprint? Maybe.

Should these static returns be declared globally (i.e., cached)?


Solution

  • They're already cached for you by the Collections class, which contains some utility methods.

    You can use Collections.emptySet(), Collections.emptyMap() and Collections.emptyList() that return immutable empty collections. Just as long as you're using the Set, Map and List interfaces in your code, as you should.

    There are also methods for returning (again immutable) collections containing a single instance, such as Collections.singletonList(mySingleElement).

    They don't really affect performance, but they do make your code clearer:

    return Collections.unmodifiableList(new ArrayList<>());
    

    vs.

    return Collections.emptyList();
    

    You can also find Collections.EMPTY_LIST etc. but when using the methods you avoid getting warnings due to (lack of) generics.