Java Collections checkedSortedSet()方法及示例
java.util.Collections 类的 checkedSortedSet() 方法用于返回指定排序集的动态类型安全视图。
如果指定的排序集是可序列化的,那么返回的排序集将是可序列化的。
由于null被认为是任何引用类型的值,只要支持的排序集允许插入null元素。
语法:
public static SortedSet checkedSortedSet(SortedSet s, Class type)
参数: 该方法接受以下参数:
- s – 要返回动态类型安全视图的排序集
- type – s允许持有的元素的类型。
返回值: 该方法返回指定排序集的动态 类型安全视图 。
以下是说明checkedSortedSet()方法的例子
例1:
// Java program to demonstrate
// checkedSortedSet() method
// for String value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of SortedMap<String>
SortedSet<String> sset = new TreeSet<String>();
// Adding element to smap
sset.add("Ram");
sset.add("Gopal");
sset.add("Verma");
// printing the sorted set
System.out.println("Sorted Set: " + sset);
// create typesafe view of the specified set
// using checkedSortedSet() method
SortedSet<String>
tsset = Collections
.checkedSortedSet(sset, String.class);
// printing the typesafe view of specified set
System.out.println("Typesafe view of sorted set: \n"
+ tsset);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出
Sorted Set: [Gopal, Ram, Verma]
Typesafe view of sorted set:
[Gopal, Ram, Verma]
例2:
// Java program to demonstrate
// checkedSortedSet() method
// for Integer value
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of SortedSet<Integer>
SortedSet<Integer> sset = new TreeSet<Integer>();
// Adding element to smap
sset.add(20);
sset.add(30);
sset.add(40);
// printing the sorted set
System.out.println("Sorted Set: " + sset);
// create typesafe view of the specified set
// using checkedSortedSet() method
SortedSet<Integer> tsset = Collections.checkedSortedSet(sset, Integer.class);
// printing the typesafe view of specified set
System.out.println("Typesafe view of sorted set: \n"
+ tsset);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出
Sorted Set: [20, 30, 40]
Typesafe view of sorted set:
[20, 30, 40]