The unmodifiableCollection() method of java.util.Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with “read-only” access to internal collections. Query operations on the returned collection “read through” to the specified collection, and attempts to modify the returned collection, whether direct or via its iterator, result in an UnsupportedOperationException.
The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object’s equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.
The returned collection will be serializable if the specified collection is serializable.
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
Parameters: This method takes the collection as a parameter for which an unmodifiable view is to be returned.
Return Value: This method returns an unmodifiable view of the specified collection.
Below are the examples to illustrate the unmodifiableCollection() method
Initial list: [X, Y]
Example 2: For UnsupportedOperationException
Initial list: [X, Y] Trying to modify the unmodifiableCollection Exception thrown : java.lang.UnsupportedOperationException