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
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
Set<String> hset = new TreeSet<String>();
hset.add( "Ram" );
hset.add( "Gopal" );
hset.add( "Verma" );
System.out.println( "Set: " + hset);
Set<String>
tsset = Collections
.checkedSet(hset, String. class );
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
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
Set<Integer> hset = new TreeSet<Integer>();
hset.add( 20 );
hset.add( 30 );
hset.add( 40 );
System.out.println( "Set: " + hset);
Set<Integer>
tsset = Collections
.checkedSet(hset, Integer. class );
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]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
06 Jun, 2021
Like Article
Save Article