Java Utility Library

Java Collections - checkedSortedSet() Method



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

Syntax

public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
                                                Class<E> type)

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


Parameters

s Specify the sorted 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 sorted set.

Exception

NA.

Example:

In the example below, the java.util.Collections.checkedSortedSet() method returns a dynamically typesafe view of the given sorted set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a SortedSet object
    SortedSet<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 a dynamically typesafe view
    //of the sorted set
    SortedSet NewSet = Collections.checkedSortedSet(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