Close

Java Collections - Collections.unmodifiableSet() Examples

[Last Updated: Dec 11, 2025]

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Method:

public static <T> Set<T> unmodifiableSet(Set<? extends T> s)

Returns an unmodifiable view of the specified Set. Attempts to modify the returned set, whether direct or via its iterator result in an UnsupportedOperationException.


Examples


Since the Set created by this method is a view of the original set, modifying the original will reflect the changes in it:

package com.logicbig.example.collections;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class UnmodifiableSetExample {

public static void main(String... args) {
Set<Integer> set = new HashSet<>();
Collections.addAll(set, 1, 4, 7);
System.out.println("Original Set: "+set);

Set<Integer> set2 = Collections.unmodifiableSet(set);
System.out.println("unmodifiableSet: "+set2);
//modifying the original
set.add(10);
System.out.println("unmodifiableSet: "+set2);
}
}

Output

Original Set: [1, 4, 7]
unmodifiableSet: [1, 4, 7]
unmodifiableSet: [1, 4, 7, 10]
JDK 25




Modifying itself will throw the exception:

package com.logicbig.example.collections;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class UnmodifiableSetExample2 {

public static void main(String... args) {
Set<Integer> set = new HashSet<>();
Collections.addAll(set, 1, 4, 7);
System.out.println("Original Set: " + set);

Set<Integer> set2 = Collections.unmodifiableSet(set);
set2.add(10);
}
}

Output

Original Set: [1, 4, 7]
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add (Collections.java:1093)
at com.logicbig.example.collections.UnmodifiableSetExample2.main (UnmodifiableSetExample2.java:21)
at jdk.internal.reflect.DirectMethodHandleAccessor.invoke (DirectMethodHandleAccessor.java:104)
at java.lang.reflect.Method.invoke (Method.java:565)
at org.codehaus.mojo.exec.AbstractExecJavaBase.executeMainMethod (AbstractExecJavaBase.java:402)
at org.codehaus.mojo.exec.ExecJavaMojo.executeMainMethod (ExecJavaMojo.java:142)
at org.codehaus.mojo.exec.AbstractExecJavaBase.doExecClassLoader (AbstractExecJavaBase.java:377)
at org.codehaus.mojo.exec.AbstractExecJavaBase.lambda$execute$0 (AbstractExecJavaBase.java:287)
at java.lang.Thread.run (Thread.java:1474)
JDK 25




See Also