Collections checkedSet() method in Java with Examples

The checkedSet() method of java.util.Collections class is used to return a dynamically typesafe view of the specified set.
The returned set will be serializable if the specified set is serializable.
Since null is considered to be a value of any reference type, the returned set permits insertion of null elements whenever the backing set does.
Syntax:Â
Â
public static Set checkedSet(Set s, Class type)
Parameters: This method takes the following argument as a parameterÂ
Â
- s: the set for which a dynamically typesafe view is to be returned
- type: the type of element that s is permitted to hold
Return Value: This method returns a dynamically typesafe view of the specified set.
Below are the examples to illustrate the checkedSet() method
Example 1:Â
Â
Java
// Java program to demonstrate// checkedSet() method// for String valueÂ
import java.util.*;Â
public class GFG1 {    public static void main(String[] argv)        throws Exception    {        try {Â
            // creating object of Set<String>            Set<String> hset = new TreeSet<String>();Â
            // Adding element to hmap            hset.add("Ram");            hset.add("Gopal");            hset.add("Verma");Â
            // print the set            System.out.println("Set: " + hset);Â
            // create typesafe view of the specified set            Set<String>                tsset = Collections                            .checkedSet(hset, String.class);Â
            // printing the typesafe view of specified list            System.out.println("Typesafe view of Set: "                               + tsset);        }        catch (IllegalArgumentException e) {Â
            System.out.println("Exception thrown : " + e);        }    }} |
Output:Â
Set: [Gopal, Ram, Verma] Typesafe view of Set: [Gopal, Ram, Verma]
Â
Example 2:Â
Â
Java
// Java program to demonstrate// checkedSet() method// for Integer valueÂ
import java.util.*;Â
public class GFG1 {    public static void main(String[] argv) throws Exception    {        try {Â
            // creating object of Set<Integer>            Set<Integer> hset = new TreeSet<Integer>();Â
            // Adding element to hset            hset.add(20);            hset.add(30);            hset.add(40);Â
            // print the set            System.out.println("Set: " + hset);Â
            // create typesafe view of the specified set            Set<Integer>                tsset = Collections                            .checkedSet(hset, Integer.class);Â
            // printing the typesafe view of specified list            System.out.println("Typesafe view of Set: " + tsset);        }        catch (IllegalArgumentException e) {Â
            System.out.println("Exception thrown : " + e);        }    }} |
Output:Â
Set: [20, 30, 40] Typesafe view of Set: [20, 30, 40]
Â



