If I have a rarely used collection in some class which may be instantiated many times, I may sometimes resort to the following \"idiom\" in order to save unnecessary object crea
Here is what I use for a helper method in some of my code. Really works nicely in reducing the ton of null checks I'd normally have to place before iterating over lists. If you want a list that wouldn't be immutable then you can return a new list object instead of Collections.emptyList
/**
* Helper method to return an empty list if provided one is null.
*
* @param list the list
* @return the provided list or an empty one if it was null
*/
private static List emptyIfNull(List list) {
if (list == null) {
return Collections.emptyList();
}
return list;
}
You then just use the helper method like so:
for (Object object : emptyIfNull(existingList)) { ... }
If the list object is null, then the helper method will return the static empty list and the contents of your loop will be skipped. This is a nice way to avoid having to create null checks wrapping any list iterations.
I've made the internals of the list be of type Object just for the example, but you'd obviously change this to be whatever makes the most sense for your usage.