List.of() — Why offer an empty list of elements that can't be add/removed/edited?

146 Views Asked by At

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()?

2

There are 2 best solutions below

0
On

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.

1
On

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