Java Collections - unmodifiableSet() Method
The java.util.Collections.unmodifiableSet() method returns an unmodifiable view of the specified set.
Syntax
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
Here, T is the type of element in the Set.
Parameters
s |
Specify the set for which an unmodifiable view is to be returned. |
Return Value
Returns an unmodifiable view of the specified set.
Exception
NA.
Example:
In the example below, the java.util.Collections.unmodifiableSet() method returns an unmodifiable view of the given set.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a set object Set<Integer> MySet = new HashSet<Integer>(); //populating the set MySet.add(10); MySet.add(20); MySet.add(30); MySet.add(40); //printing the set System.out.println("MySet contains: " + MySet); //creating an unmodifiable view of the set Set NewSet = Collections.unmodifiableSet(MySet); //printing the unmodifiable set System.out.println("NewSet contains: " + NewSet); //trying to modify the NewSet NewSet.add(50); } }
The output of the above code will be:
MySet contains: [20, 40, 10, 30] NewSet contains: [20, 40, 10, 30] Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1060) at MyClass.main(MyClass.java:24)
❮ Java.util - Collections