Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.of()

Creates an unmodifiable list from the listed elements.

Available since: Java 9

Syntax

static <E> List<E> of(E... elements)

Parameters

ParameterTypeDescription
elementsE...The elements of the new list. `null` is not allowed.

Return value

List<E>An unmodifiable list holding the given elements in the same order.

Examples

A list of three strings:

void main() {
    List<String> names = List.of("Anna", "Oleg", "Ivan");
    IO.println(names);
    IO.println(names.size());
}

Output:

[Anna, Oleg, Ivan]
3

Such a list cannot be changed, so make a copy in an ArrayList:

void main() {
    List<Integer> fixed = List.of(3, 1, 2);
    try {
        fixed.add(4);
    } catch (UnsupportedOperationException e) {
        IO.println("Cannot add: " + e);
    }
    List<Integer> copy = new ArrayList<>(fixed);
    copy.add(4);
    IO.println(copy);
}

Output:

Cannot add: java.lang.UnsupportedOperationException
[3, 1, 2, 4]

Notes

Any attempt to change the list — add(), remove(), set(), sort() — throws UnsupportedOperationException. null elements are forbidden: List.of(null) throws NullPointerException. For a modifiable list wrap the result: new ArrayList<>(List.of(...)).

See also

  • ArrayList — A resizable list backed by an array — the most common `List` implementation.
  • List.copyOf() — Creates an unmodifiable list copy of a collection.
  • Set.of() — Creates an unmodifiable set from the listed elements.
  • Map.of() — Creates an unmodifiable map from key and value pairs.
  • UnsupportedOperationException — Thrown when an operation is not supported by the object, such as changing an unmodifiable collection.

Related recipes

In the tutorial

  • Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.

Thanks for reading!

Donate to the site — we work hard for you.