VOOZH about

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

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


  • Courses
  • Tutorials
  • Interview Prep

Collections unmodifiableSet() method in Java with Examples

Last Updated : 8 Oct, 2018
The unmodifiableSet() method of java.util.Collections class is used to return an unmodifiable view of the specified set. This method allows modules to provide users with "read-only" access to internal sets. Query operations on the returned set "read through" to the specified set, and attempts to modify the returned set, whether direct or via its iterator, result in an UnsupportedOperationException. The returned set will be serializable if the specified set is serializable. Syntax:
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
Parameters: This method takes the set as a parameter for which an unmodifiable view is to be returned. Return Value: This method returns an unmodifiable view of the specified set. Below are the examples to illustrate the unmodifiableSet() method Example 1:
Output:
unmodifiable Set: [X, Y]
Example 2: For UnsupportedOperationException
Output:
unmodifiable Set: [X, Y]

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

Explore