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?
collectionsempty-listjava
Best Answer
The main difference is that
Collections.emptyList()
returns an immutable list, i.e., a list to which you cannot add elements. (Same applies to theList.of()
introduced in Java 9.)In the rare cases where you do want to modify the returned list,
Collections.emptyList()
andList.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.The implementation of
emptyList
looks as follows: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.