Java: Collections.emptyList vs new ArrayList

The main difference between new ArrayList<>() and Collections.emptyList() (or the slightly shorter variant List.of() introduced in JDK 9) is that the latter returns an immutable list, i.e., a list to which you cannot add elements.

In addition, Collections.emptyList()/List.of() avoids creating a new object. From the javadoc:

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 standard implementation of emptyList looks as follows:

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

So if this is a hotspot in your code, there’s even a small performance argument to be made.

In summary I’d say List.of is preferrable (if you’re on 9) over Collections.emptyList, which is preferable over for instance new ArrayList<>().

Comments