Java Utility Library

Java Collections - checkedNavigableSet() Method



The java.util.Collections.checkedNavigableSet() method returns a dynamically typesafe view of the specified navigable set. Any attempt to insert an element of the wrong type will result in an immediate ClassCastException.

Syntax

public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
                                                      Class<E> type)

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


Parameters

s Specify the navigable set for which a dynamically typesafe view is to be returned.
type Specify the type of element that s is permitted to hold.

Return Value

Returns a dynamically typesafe view of the specified navigable set.

Exception

NA.

Example:

In the example below, the java.util.Collections.checkedNavigableSet() method returns a dynamically typesafe 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(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

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

    //creating a dynamically typesafe view
    //of the navigable set
    NavigableSet NewSet = Collections.checkedNavigableSet(MySet, Integer.class);

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

The output of the above code will be:

MySet contains: [10, 20, 30, 40]
NewSet contains: [10, 20, 30, 40]

❮ Java.util - Collections