What it is and why to use it
Collections.unmodifiableList wraps a list and prohibits modification through that wrapper. It is useful when consumers should observe a changing list without receiving write methods that succeed. Unlike List.copyOf, it is a view backed by the original collection.
How it works
Both source and view reach the same underlying list contents. Adding through source is visible through view. Attempting to add, remove or replace through view throws UnsupportedOperationException. The wrapper does not provide synchronisation or stop other references from mutating the backing list.
Common mistakes and limitations
Do not advertise a live view as an independent snapshot. An unmodifiable wrapper is also not a thread-safety mechanism, and mutable element objects can still change.
Try it and keep learning
Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.
Syntax
List<String> view = Collections.unmodifiableList(source);Examples
Unmodifiable Views versus Copies
Complete Main.java example — Java 17 or later, without preview features.
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("Draft"));
List<String> view = Collections.unmodifiableList(source);
source.add("Review");
System.out.println(view);
System.out.println(List.copyOf(view));
}
}- The wrapper is created while source contains Draft.
- Adding Review through source appears in view because the view is backed by source.
- copyOf captures the two elements at that moment. It looks identical when printed now, but future structural changes to source would affect view and not the copy.
- Expected output: [Draft, Review] [Draft, Review]
Best practices
- Choose explicitly between a live view and a snapshot.
- Keep ownership of the backing list clear.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification