Java.util.Collections 类

java.util.Collections.checkedSortedSet() 方法返回指定排序集的动态类型安全视图。任何插入错误类型元素的尝试都将立即导致 ClassCastException。

语法

public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
                                                Class<E> type)

这里,E 是排序集中元素的类型。

参数

s 指定要返回动态类型安全视图的排序集。
type 指定 s 允许保存的元素类型。

返回值

返回指定排序集的动态类型安全视图。

异常

无。

示例:

在下面的示例中,java.util.Collections.checkedSortedSet() 方法返回给定排序集的动态类型安全视图。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建一个SortedSet对象
    SortedSet<Integer> MySet = new TreeSet<Integer>();

    //填充集合
    MySet.add(30);
    MySet.add(20);
    MySet.add(10);
    MySet.add(40);

    //打印集合
    System.out.println("MySet contains: " + MySet); 

    //创建动态类型安全视图
    //排序集
    SortedSet NewSet = Collections.checkedSortedSet(MySet, Integer.class);

    //打印集合
    System.out.println("NewSet contains: " + NewSet); 
  }
}

上述代码的输出将是:

MySet contains: [10, 20, 30, 40]
NewSet contains: [10, 20, 30, 40]