Java Collections checkedSet()方法及示例
java.util.Collections 类的 checkedSet() 方法用于返回指定集合的动态类型安全视图。如果指定的集合是可序列化的,那么返回的集合将是可序列化的。
因为null被认为是任何引用类型的值,所以只要支持的集合允许插入null元素。
语法:
public static Set checkedSet(Set s, Class type)
参数: 该方法接受以下参数作为参数
- s: 要返回的动态类型安全视图的集合
- type: s允许持有的元素的类型。
返回值: 该方法返回指定集合的动态 类型安全视图
以下是说明checkedSet()方法的例子
例1:
// 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);
}
}
}
输出
Set: [Gopal, Ram, Verma]
Typesafe view of Set: [Gopal, Ram, Verma]
例2:
// 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);
}
}
}
输出
Set: [20, 30, 40]
Typesafe view of Set: [20, 30, 40]