Close

Java Collections - Collections.unmodifiableSet() Examples

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]




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

Caused by: java.lang.UnsupportedOperationException
at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1056)
at com.logicbig.example.collections.UnmodifiableSetExample2.main(UnmodifiableSetExample2.java:21)
... 6 more




See Also