List.of() or Collections.emptyList()

Sormuras :

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

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 if those happen for some odd reason.
  • 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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=447220&siteId=1