1

One of the Java 9 features I've tested is the List.of() to create an unmodifiable list. I wonder - What is the purpose of this method if it returns an empty list of elements that can't be add / removed / edited?

The only thing that i was able to think of is to compare this list to another empty list, but then why not just to use someList.isEmpty()?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Fima Taf
  • 929
  • 9
  • 22
  • There's nothing special or strange about lists with zero elements, whether or not they're modifiable. If you asked me for a list of elephants in my household, I would give you `List.of()` because I have zero and I definitely don't want you adding to my collection. – that other guy Sep 30 '18 at 02:05

2 Answers2

3

First of all, List.of() does not create any new object. It refers to a static final constant, as we can see in the OpenJDK source code List.java.

static <E> List<E> of() {
    return ImmutableCollections.List0.instance();
}

…and in the source code for java.util.ImmutableCollections.List0.instance():

static <T> List0<T> instance() 
   return (List0<T>) INSTANCE;
}

List.of() can used to return an empty list instead of a null, which has numerous advantages:

  • elimates the risk of NullPointerException
  • the client code does not have to check for null
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
  • For discussion, see [*Is it better to return null or empty collection?*](https://stackoverflow.com/questions/1969993/is-it-better-to-return-null-or-empty-collection). That page is for C# rather than Java, but same issues involved. – Basil Bourque Sep 29 '18 at 21:54
-3

As far as I know, the primary use of this method is for debugging. If you want to test your code on some list (say summing the elements), it is convenient to have a method that quickly creates a list. Because of the internal implementation the list is not mutable, but that's okay since we're just using it to test your code once.

UPDATE:

Since List.of(E e1, E e2, ...) are used for debugging, there is no reason not to include List.of() with no arguments, as often when debugging you will check for edge cases and see if your code also works for empty lists.

Alexander Wu
  • 433
  • 4
  • 8