Close

Java Collections - Collections.unmodifiableSortedSet() Examples

Java Collections Java Java API 


Class:

java.util.Collections

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

Method:

public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)

Returns an unmodifiable view (read-only) of the specified SortedSet. Attempts to modify the returned set, whether direct or via its iterator or via subSet, headSet, or tailSet views , 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.SortedSet;
import java.util.TreeSet;

public class UnmodifiableSortedSetExample {

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

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

Output

Original Set: [1, 4, 7]
unmodifiableSortedSet: [1, 4, 7]
unmodifiableSortedSet: [1, 4, 7, 10]




Modifying itself will throw exception:

package com.logicbig.example.collections;

import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

public class UnmodifiableSortedSetExample2 {

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

SortedSet<Integer> set2 = Collections.unmodifiableSortedSet(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.UnmodifiableSortedSetExample2.main(UnmodifiableSortedSetExample2.java:21)
... 6 more




See Also