Java Utility Library

Java Collections - unmodifiableSortedSet() Method



The java.util.Collections.unmodifiableSortedSet() method returns an unmodifiable view of the specified sorted set.

Syntax

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

Here, T is the type of element in the sorted set.


Parameters

s Specify the sorted set for which an unmodifiable view is to be returned.

Return Value

Returns an unmodifiable view of the specified sorted set.

Exception

NA.

Example:

In the example below, the java.util.Collections.unmodifiableSortedSet() method returns an unmodifiable view of the given sorted set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a SortedSet object
    SortedSet<Integer> MySet = new TreeSet<Integer>();

    //populating the set
    MySet.add(30);
    MySet.add(20);
    MySet.add(10);
    MySet.add(40);

    //printing the set
    System.out.println("MySet contains: " + MySet); 

    //creating an unmodifiable view of the sorted set
    SortedSet NewSet = Collections.unmodifiableSortedSet(MySet);

    //printing the unmodifiable sorted 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: [10, 20, 30, 40]
NewSet contains: [10, 20, 30, 40]

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