Thursday, August 28, 2025
HomeLanguagesJavaJava Collections checkedNavigableSet() Method with Examples

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:

  • set is an input set data
  • datatype is the type of elements that set can hold

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

Exceptions:

  • ClassCastException: ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another.

Example 1: 

Java




// 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




// 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]
RELATED ARTICLES

Most Popular

Dominic
32244 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6615 POSTS0 COMMENTS
Nicole Veronica
11787 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11831 POSTS0 COMMENTS
Shaida Kate Naidoo
6726 POSTS0 COMMENTS
Ted Musemwa
7008 POSTS0 COMMENTS
Thapelo Manthata
6683 POSTS0 COMMENTS
Umr Jansen
6696 POSTS0 COMMENTS