Collections.emptyList() vs. new instance

JavaCollectionsEmpty List

Java Problem Overview


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

return Collections.emptyList();

Or like [this][2]:

return new ArrayList<Foo>();

Or is this completely dependent upon what you're going to do with the returned list? [1]: http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#emptyList%28%29 [2]: http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28%29

Java Solutions


Solution 1 - Java

The main difference is that Collections.emptyList() returns an immutable list, i.e., a list to which you cannot add elements. (Same applies to the List.of() introduced in Java 9.)

In the rare cases where you do want to modify the returned list, Collections.emptyList() and List.of() are thus not a good choices.

I'd say that returning an immutable list is perfectly fine (and even the preferred way) as long as the contract (documentation) does not explicitly state differently.


In addition, emptyList() might not create a new object with each call. >Implementations of this method need not create a separate List object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)

The implementation of emptyList looks as follows:

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

So if your method (which returns an empty list) is called very often, this approach may even give you slightly better performance both CPU and memory wise.

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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();

Solution 7 - Java

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmreView Question on Stackoverflow
Solution 1 - JavaaioobeView Answer on Stackoverflow
Solution 2 - JavaPaul JacksonView Answer on Stackoverflow
Solution 3 - JavaJeff FosterView Answer on Stackoverflow
Solution 4 - JavaSergey FrolovView Answer on Stackoverflow
Solution 5 - JavaS73417HView Answer on Stackoverflow
Solution 6 - JavaAtulView Answer on Stackoverflow
Solution 7 - JavaRenéView Answer on Stackoverflow