The following might be totally obvious, but to me it was a revelation, so why not publish it.
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:
- 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.
blog comments powered by Disqus