Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collections.unmodifiableList()

Returns a view of a list that cannot be modified.

Available since: Java 1.2

Syntax

static <T> List<T> unmodifiableList(List<? extends T> list)

Parameters

ParameterTypeDescription
listList<? extends T>The list to protect from changes.

Return value

List<T>A read-only view.

Examples

The wrapper cannot be changed, but changes to the original show through:

void main() {
    List<String> source = new ArrayList<>(List.of("a", "b"));
    List<String> readOnly = Collections.unmodifiableList(source);
    try {
        readOnly.add("c");
    } catch (UnsupportedOperationException e) {
        IO.println("read-only");
    }
    source.add("c");
    IO.println(readOnly);
}

Output:

read-only
[a, b, c]

Notes

It is not a copy but a read-only window: the original list can still change, and the changes show through the wrapper. For an independent unmodifiable copy use List.copyOf(). Counterparts for other collections: unmodifiableSet(), unmodifiableMap().

See also

  • List.copyOf() — Creates an unmodifiable list copy of a collection.
  • List.of() — Creates an unmodifiable list from the listed elements.
  • UnsupportedOperationException — Thrown when an operation is not supported by the object, such as changing an unmodifiable collection.

Related recipes

In the tutorial

  • Collection helper methods — The Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.

Thanks for reading!

Donate to the site — we work hard for you.