Java Utility Library

Java Collections - unmodifiableNavigableSet() Method



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

Syntax

public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s)

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


Parameters

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

Return Value

Returns an unmodifiable view of the specified navigable set.

Exception

NA.

Example:

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

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a NavigableSet object
    NavigableSet<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 navigable set
    NavigableSet NewSet = Collections.unmodifiableNavigableSet(MySet);

    //printing the unmodifiable navigable 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