Java Collections checkedSortedSet()
checkedSortedSet()是
Java集合类的内置方法。此方法用于获取指定排序集的动态类型安全视图。
语法
以下是
checkedSortedSet()的声明方法:
public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type)
参数
参数 |
说明 |
必需/可选 |
s |
这是要为其返回动态类型安全视图的排序集。 |
必需 |
type |
这是允许s保留的元素的类型。 |
必需 |
返回
checkedSortedSet()方法会自动以升序返回指定排序集的动态类型安全视图。
异常
ClassCastException
兼容版本
Java 1.5及更高版本
示例1
import java.util.*;
public class CollectionsCheckedSortedSetExample1 {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet<String>();
//Insert values in the Set
set.add("lidihuo");
set.add("Hindi100");
set.add("SSSIT");
set.add("JavaTraining");
//Get type safe view of the Set
System.out.println("Type safe view of the Sorted Set is: "+Collections.checkedSortedSet(set,String.class));
}
}
输出:
Type safe view of the Set is: [Hindi100, lidihuo, JavaTraining, SSSIT]
示例2
import java.util.*;
public class CollectionsCheckedSortedSetExample2 {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
//Insert values in the Set
set.add(1100);
set.add(100);
set.add(500);
set.add(200);
//Get type safe view of the Set
SortedSet<Integer> TypeSafeSet;
TypeSafeSet = Collections.checkedSortedSet(set,Integer.class);
System.out.println("The view of the Sorted Set is: "+TypeSafeSet);
}
}
输出:
The view of the Sorted Set is: [100, 200, 500, 1100]
示例3
import java.util.*;
public class CollectionsCheckedSortedSetExample3 {
public static void main(String[] args) {
SortedSet<Integer> set = new TreeSet<>();
set = Collections.checkedSortedSet(set, Integer.class);
set.add(1100);
set.add(5000);
set.add(800);
System.out.println("Dynamic type safe view of Sorted Set is: "+set);
Set set2 = set;
set2.add("SSSIT.COM");
System.out.println(set2);
}
}
输出:
Dynamic type safe view of Sorted Set is: [800, 1100, 5000]
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.String element into collection with element type class java.lang.Integer
at java.base/java.util.Collections$CheckedCollection.typeCheck(Collections.java:3038)
at java.base/java.util.Collections$CheckedCollection.add(Collections.java:3081)
at myPackage.CollectionCheckedSortedSetExample3.main(CollectionCheckedSortedSetExample3.java:12)