![]() |
VOOZH | about |
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
Original List: [A, B] Unmodifiable List: [A, B]
public static <T> List<T> unmodifiableList(List<? extends T> list)
Parameters
Return Value: Returns an unmodifiable view of the specified list. Any modification attempt on this view will throw an exception.
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.
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.