CKTIS / Java
Collections.unmodifiableList — an unmodifiable list view
Block writes through a list view without freezing the source. To keep later edits to the source out of the view, wrap a private copy instead.
Version: Java SE 21
Syntax
public static <T> List<T> unmodifiableList(List<? extends T> list)
// Widok listy źródłowej / View of the source list
List<T> view = Collections.unmodifiableList(source);
// Widok prywatnej kopii / View of a private copy
List<T> snapshot = Collections.unmodifiableList(new ArrayList<>(source));Collections.unmodifiableList is a static method on java.util.Collections. It takes a List<? extends T> and returns a List<T>. Passing null instead of a list throws NullPointerException. The result still has type List: calls such as add and set compile, but attempts to modify the list through the view, including through its iterator, throw UnsupportedOperationException at run time.
Reads go to the backing list. If code retains access to that list and adds, removes, or replaces an element, subsequent reads through the view show the change. Use this pattern when callers should see the current list but must not be able to edit it through the reference you give them.
To preserve which elements the list contains and in what order at copy time, use Collections.unmodifiableList(new ArrayList<>(source)). Do not expose or later modify the mutable copy. The result is still a view, but its backing list is the private copy, not the original. The copy is shallow: shared mutable elements can still change state. The wrapper does not add synchronization.
List.copyOf(source) is another option: it returns an unmodifiable list that does not reflect later changes to the source list, and it does not deep-copy the elements. It rejects null elements with NullPointerException; a view of a private copy made with new ArrayList<>(source) preserves them.
Examples
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("A", "B"));
List<String> live = Collections.unmodifiableList(source);
List<String> snapshot = Collections.unmodifiableList(new ArrayList<>(source));
source.set(0, "X");
source.add("C");
System.out.println("live: " + live);
System.out.println("snapshot: " + snapshot);
try {
live.set(0, "Y");
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException");
}
}
}Result
live: [X, B, C] snapshot: [A, B] UnsupportedOperationException
`source.set` and `source.add` change what `live` reads but not what `snapshot` reads. `live.set` compiles but throws `UnsupportedOperationException`.
Related lessons
- Java · Lesson 2 · Advanced · Version: 2
- Java · Lesson 21 · Advanced · Version: 2