Friday, 10 June 2011

Collections.emptyList() vs new ArrayList(), Collections.emptyMap() vs new HashMap(), Collections.emptySet() vs new HashSet()

Collections.empty{List,Map,Set}() return immutable collections, i.e. collections that cannot be edited. 

Why is returning an empty and immutable Collection often preferable to returning a null or even to returning a mutable collection? The most obvious disadvantage of returning a null is forcing the client of the method to deal with that null. The most obvious advantage to an immutable collection is the advantages associated with immutable objects and collections in concurrent programming.


Also add here the fact that is faster calling Collections.empty{List,Map,Set}() for initializing a collection.

Hint: If you have a code such as the following then usage of Collections.empty{List,Map,Set}() is recommended.

public void foo() {
List collection = Collections.emptyList();
try {
 collection = load collection from db or elsewhere;
} catch(Exception e) {
return collection; //in case of an exception the collection is empty


No comments:

Post a Comment