The following might be totally obvious, but to me it was a revelation, so why not publish it. :-)

There are situations when you have methods returning a collection.
A Java collection can be a set (no sorting, no duplicates), a list (sorting, duplicates) or a map (association key/value).

In some cases, the method might fail.
To have robust code, you would still like to return an empty set, list or collection instead of null.

Instead of creating your own “empty collection” every time, you can use the utilities from java.util.Collections:

This will

  • Make code more readable, because you just use one of the above instead of a painful collection instantiation
  • Use super-efficient implementations. The returned collections are immutable, because they are not actually collections — they are just objects providing the collection interfaces. E.g. calls to contains(Object) will always return false instead of iterating over an empty list.

I hope this can help you as much as it helped me. :-)

There’s a caveat, of course.
The collections being immutable also implies that you can’t add any elements.
So these empty collections can be used only in situations where you are sure that the collection will not be modified later.
Modification will (fortunately) throw an UnsupportedOperationException.

Another noteworthy thing in the Collections utilities are the singleton, singletonList and singletonMap methods.
These return a set, list or map with exactly one element.

Are you interested in reading more from CodingClues?
Then subscribe to new postings via RSS or via E-Mail.

close Reblog this comment
blog comments powered by Disqus