Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.of() or Collections.emptyList()

As an special case of List.of(...) or Collections.unmodifiableList() - what is the preferred Java 9 way of pointing to an empty and immutable list?

Keep writing

Collections.emptyList();

or switch to

List.of();
like image 847
Sormuras Avatar asked Sep 08 '16 21:09

Sormuras


People also ask

What is the use of collections emptyList ()?

The emptyList() method of Java Collections returns the list with no elements. This method is immutable.

What is the difference between collections emptyList () and creating new instance of collection?

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.

How do you empty a list in Java?

clear() method removes all of the elements from this list. The list will be empty after this call returns.


3 Answers

Collections.emptyList() does not need to create a new object for each call; it's typical, as in OpenJDK, to just return the singleton EMPTY_LIST object. Additionally, it's clearer that you intend to mean an empty list rather than having forgotten to fill in a placeholder.

Use emptyList(); it's both faster (up to Java target level 1.9) and more readable.

like image 137
chrylis -cautiouslyoptimistic- Avatar answered Oct 16 '22 05:10

chrylis -cautiouslyoptimistic-


What is the preferred Java 9 way of pointing to an empty and immutable list?

The difference is rather subtle so "preferred" depends on what you want to achieve. Some behavioral differences:

  • List.of will throw an exception on contains(null) invocations.
  • You can deserialize emptyList() on JDK 8 and previous, but not List.of.

In terms or conveying that you want an empty list, emptyList() might look better, but this is just a temporary convention. If developers start using List.of() (which is much shorter than Collections.emptyList()) then it will become a known and accepted way, it's just new. If you think about it, there are some constructs we use which do not always convey what they do by themselves, but we got accustomed to them.

So there is no strictly preferred way. If the behavior does not matter use whatever you want.

like image 28
user1803551 Avatar answered Oct 16 '22 06:10

user1803551


  1. emptyList() creates a new empty list instance only once
  2. there is no difference on Readability: maybe List.of() is shorten than Collections.emptyList() but you can use a static import like import static java.util.Collections.emptyList; and then write only emptyList()
like image 2
Andrea Ciccotta Avatar answered Oct 16 '22 05:10

Andrea Ciccotta