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.

[http://marxsoftware.blogspot.com/2008/05/using-collections-methods-emptylist.html


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
}

Rerefences< http://gochev.blogspot.com/2010/07/using-of-collectionsemptylist-right-way.html

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Collections.html

http://marxsoftware.blogspot.com/2008/05/using-collections-methods-emptylist.html

No comments:

Post a Comment