Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

List.of and List.of() — unmodifiable lists

`List.of` creates an unmodifiable list from the supplied elements. The no-argument `List.of()` returns an empty list. None of the overloads accepts `null` elements.

Version: Java SE 21

Syntax

import java.util.List;

List<E> empty = List.of();
List<E> values = List.of(e1, e2);

// Factory method signatures (E is the element type):
// static <E> List<E> of()
// static <E> List<E> of(E e1, ..., E eN)  [one overload for each N from 1 to 10]
// static <E> List<E> of(E... elements)

List.of is a family of static factory methods on the java.util.List interface, available since Java 9. List.of() is the no-argument overload: it returns an empty, unmodifiable list you can pass wherever a list is expected and there are no elements to supply. In List<String> empty = List.of();, Java infers the element type from the variable's declared type.

There are fixed-arity overloads for 1–10 elements and a varargs overload, of(E... elements), for any number of elements. The list preserves argument order and allows duplicates. If any supplied element is null, the factory call throws NullPointerException instead of returning a list.

Calling add, remove, or set on the returned list throws UnsupportedOperationException, even if the list is empty. An unmodifiable list does not make the objects it holds immutable. If you need to add, remove, or replace elements, make a shallow, modifiable copy with new ArrayList<>(source).

Examples

import java.util.ArrayList;
import java.util.List;

public class ListOfDemo {
    public static void main(String[] args) {
        List<String> empty = List.of();
        List<String> colors = List.of("red", "blue", "red");
        System.out.println("Empty size: " + empty.size());
        System.out.println("Colors: " + String.join(", ", colors));

        try {
            colors.set(0, "green");
        } catch (UnsupportedOperationException expected) {
            System.out.println("UnsupportedOperationException");
        }

        try {
            List.of("red", null);
        } catch (NullPointerException expected) {
            System.out.println("NullPointerException");
        }

        List<String> editable = new ArrayList<>(empty);
        editable.add("green");
        System.out.println("Mutable copy: " + editable.get(0));
        System.out.println("Original size: " + empty.size());
    }
}

Result

Empty size: 0
Colors: red, blue, red
UnsupportedOperationException
NullPointerException
Mutable copy: green
Original size: 0

The example shows an empty list, preserved order and duplicates, and two different exceptions. Adding to the modifiable copy leaves the empty source unchanged.

Related lessons

  • Java · Lesson 67 · Basic · Version: 2
  • Java · Lesson 34 · Intermediate · Version: 2
  • Java · Lesson 43 · Intermediate · Version: 2

Sources