VOOZH about

URL: https://www.geeksforgeeks.org/advance-java/collections-unmodifiablelist-method-in-java-with-examples/

⇱ Collections unmodifiableList() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collections unmodifiableList() method in Java with Examples

Last Updated : 8 Nov, 2025

The unmodifiableList() method of the java.util.Collections class is used to create a read-only view of a specified list. It is particularly useful when you want to share a list with other parts of the application but prevent them from modifying its contents.

Any attempt to modify the returned list, either directly or through its iterator, will result in an UnsupportedOperationException.

Basic unmodifiableList() usage


Output
Original List: [A, B]
Unmodifiable List: [A, B]
  • The unmodifiableList() method returns a read-only view of the original list.
  • You can still modify the original list, and those changes will reflect in the unmodifiable view.

Method Definition

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

Parameters

  • list: The list for which an unmodifiable view is to be returned.

Return Value: Returns an unmodifiable view of the specified list. Any modification attempt on this view will throw an exception.

Key Points

  • The returned list reflects any changes made to the original list (since it’s a view, not a copy).
  • It does not allow structural modification such as add(), remove(), or clear().
  • The returned list is serializable if the original list is serializable.
  • If the provided list implements RandomAccess, the returned list also implements it.

Attempting to Modify the Unmodifiable List


Output
Initial List: [X, Y]

Trying to modify the unmodifiable list...
Exception thrown: java.lang.UnsupportedOperationException

When you try to add, remove, or alter the unmodifiable list, Java throws an UnsupportedOperationException, indicating that modification is not allowed.

Reflecting Changes from Original List


Output
Original List: [Delhi, Mumbai]
Unmodifiable List: [Delhi, Mumbai]

After modifying the original list:
Original List: [Delhi, Mumbai, Chennai]
Unmodifiable List: [Delhi, Mumbai, Chennai]

Even though the returned list is unmodifiable, it is still backed by the original list. Therefore, any modification to the original list is reflected in the unmodifiable view.

When to Use unmodifiableList()

  • When exposing internal collections to external modules while ensuring they cannot be modified.
  • When creating immutable views for read-only operations.
  • When working in multi-layered applications where one layer should not alter another layer’s data.
Comment

Explore