Java Utility Library

Java Collections - checkedSet() Method



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

Syntax

public static <E> Set<E> checkedSet(Set<E> s,
                                    Class<E> type)

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


Parameters

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

Exception

NA.

Example:

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

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a Set object
    Set<Integer> MySet = new HashSet<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 set
    Set NewSet = Collections.checkedSet(MySet, Integer.class);

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

The output of the above code will be:

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

❮ Java.util - Collections