Collections.unmodifiableList: Read-Only Lists
You'll learn how to create read-only views of lists that prevent any modifications and throw exceptions when changes are attempted.
What Is an Unmodifiable List?
An unmodifiable list is a wrapper around an existing list that blocks all modification attempts. Think of it like putting a museum display case around a valuable artifact—you can look at it, examine it, and show it to others, but you absolutely cannot touch or change it.
When you call Collections.unmodifiableList(), you get a view of your original list that prevents operations like add, remove, set, or clear. Any attempt to modify the list through this view throws an UnsupportedOperationException.
How It Works
The unmodifiable wrapper doesn't copy your list—it creates a protective layer around the original. All read operations (like get, size, contains) work normally, but write operations are blocked:
List<String> original = new ArrayList<>();
original.add("Java");
original.add("Python");
original.add("JavaScript");
List<String> readOnly = Collections.unmodifiableList(original);
// Reading works fine
System.out.println(readOnly.get(0)); // "Java"
System.out.println(readOnly.size()); // 3
// Modification attempts throw UnsupportedOperationException
readOnly.add("Ruby"); // THROWS EXCEPTION
readOnly.remove(0); // THROWS EXCEPTION
readOnly.set(1, "Kotlin"); // THROWS EXCEPTION
readOnly.clear(); // THROWS EXCEPTION
Important Caveat
Changes to the original list are still reflected in the unmodifiable view, because they share the same underlying data. The wrapper only prevents modifications through itself.
When to Use It
Use unmodifiable lists when you want to share a list with other code but guarantee they cannot alter your data—perfect for returning collections from methods without risking external mutation.
Key Takeaway: Collections.unmodifiableList() creates a read-only wrapper that allows querying but blocks all modifications with UnsupportedOperationException, protecting your data from unwanted changes.