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