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?
Solution 1:
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:
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.