[java] Collections.emptyList() vs. new instance

In practice, is it better to return an empty list like this:

return Collections.emptyList();

Or like this:

return new ArrayList<Foo>();

Or is this completely dependent upon what you're going to do with the returned list?

This question is related to java collections empty-list

The answer is


Use Collections.emptyList() if you want to make sure that the returned list is never modified.

This is what is returned on calling emptyList():

/**
 * The empty list (immutable). 
 */
public static final List EMPTY_LIST = new EmptyList();

Starting with Java 5.0 you can specify the type of element in the container:

Collections.<Foo>emptyList()

I concur with the other responses that for cases where you want to return an empty list that stays empty, you should use this approach.


The given answers stress the fact that emptyList() returns an immutable List but do not give alternatives. The Constructor ArrayList(int initialCapacity) special cases 0 so returning new ArrayList<>(0) instead of new ArrayList<>() might also be a viable solution:

/**
 * Shared empty array instance used for empty instances.
 */
private static final Object[] EMPTY_ELEMENTDATA = {};

[...]

/**
 * Constructs an empty list with the specified initial capacity.
 *
 * @param  initialCapacity  the initial capacity of the list
 * @throws IllegalArgumentException if the specified initial capacity
 *         is negative
 */
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

(sources from Java 1.8.0_72)


Collections.emptyList is immutable so there is a difference between the two versions so you have to consider users of the returned value.

Returning new ArrayList<Foo> always creates a new instance of the object so it has a very slight extra cost associated with it which may give you a reason to use Collections.emptyList. I like using emptyList just because it's more readable.


I would go with Collections.emptyList() if the returned list is not being modified in any way (as the list is immutable), otherwise I would go with option 2.

The benefit of Collections.emptyList() is that the same static instance is returned each time and so there is not instance creation occurring for each call.


Be carefully though. If you return Collections.emptyList() and then try to do some changes with it like add() or smth like that, u will have an UnsupportedOperationException() because Collections.emptyList() returns an immutable object.