Collections.emptyList() instead of null check?

in order to save unnecessary object creations

That's a really bad idea which will litter your code with == null checks and other handling of corner cases (and presumably end up in null pointer exceptions anyway)!

Now I was wondering if I couldn't eliminate those null checks using Collections.emptyList()

No, not really. emptyList() returns an empty list. You could do

if (list.equals(Collections.<Object>emptyList()))

but that will still throw a NullPointerException if list == null, so it's still not what you're after.

My recommendation: Always initialize the list to new ArrayList<Object>, or, if you for instance want to return an empty list from a method, use Collections.emptyList() instead. (This returns the same instance every time, so no unnecessary object creation there either.)

And then use .isEmpty() to check if a collection is empty or not.


The suggested answers are absolutely correct, just small tip - in Java 8 you can use the new Optional class to handle the case where the list instance is null, in a more functional approach.

For example, something like this:

public static List<String> addElement(List<String> list, String toAdd) {
       List<String> newList = Optional.ofNullable(list).orElse(new ArrayList<>());
       newList.add(toAdd);
       return newList;
}

Following a tip in the comments, it's better to replace new ArrayList<>() with Collections.emptyList() in order to prevent the creation of a new instance of an empty ArrayList

public static List<String> addElement(List<String> list, String toAdd) {
   List<String> newList = Optional.ofNullable(list).orElse(Collections.emptyList());
   newList.add(toAdd);
   return newList;
}

There is an emptyIfNull method in package org.apache.commons.collections4;. It returns an empty list if the one provided is null.

List<Object> list = CollectionUtils.emptyIfNull(list);

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 <T> List<T> emptyIfNull(List<T> 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.