Open In App

Java Collections checkedNavigableSet() Method with Examples

The checkedQueue() method of Java Collections is a method that returns a  dynamically and typesafe view of the given 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> set, Class<E> datatype)

Parameters:

Return Type: This method will return the dynamically and typesafe view of the given Set.



Exceptions:

Example 1: 




// Java program to create a Tree set and
// display the elements in a typesafe way
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // create a set of string type
        NavigableSet<String> data = new TreeSet<>();
  
        // Insert the values into the set
        data.add("java");
        data.add("php/jsp");
        data.add("python");
        data.add("R");
  
        // type safe view of the set
        System.out.println(Collections.checkedNavigableSet(
            data, String.class));
    }
}

Output
[R, java, php/jsp, python]

Example 2:




// Java program to create a Tree set and
// display the elements in a typesafe way
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // create a set of string type
        NavigableSet<Integer> data = new TreeSet<>();
  
        // Insert the values into the set
        data.add(1);
        data.add(2);
        data.add(3);
        data.add(4);
  
        // type safe view of the set
        System.out.println(Collections.checkedNavigableSet(
            data, Integer.class));
    }
}

Output
[1, 2, 3, 4]

Article Tags :