Java教程

Java Collections checkedSet()

checkedSet()是Java Collections 类的内置方法。此方法用于获取指定Set的动态类型安全视图。

语法

以下是 checkedSet()方法的声明:
public static <E> Set<E> checkedSet(Set<E> s, Class<E> type)

参数

参数 说明 必需/可选
s 这是要为其返回动态类型安全视图的集合。 必需
type 这是允许s保留的元素的类型。 必需

返回

checkedSet()方法会自动以升序返回指定Set的动态类型安全视图。

异常

ClassCastException

兼容版本

Java 1.5及更高版本
示例1
import java.util.*;
public class CollectionsCheckedSetExample1 {
    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 Set is: "+Collections.checkedSet(set,String.class));
          }
}
输出:
Type safe view of the Set is: [Hindi100, lidihuo, JavaTraining, SSSIT]

示例2

import java.util.*;
public class CollectionsCheckedSetExample2 {
    public static void main(String[] args) {
        TreeSet<Integer> set = new TreeSet<>();
        //Insert values in the Set
        set.add(1100);
        set.add(2200);
        set.add(500);
        set.add(900);
          //Get type safe view of the Set  
        Set<Integer> TypeSafeSet;
        TypeSafeSet = Collections.checkedSet(set,Integer.class);
          System.out.println("The view of the Set is: "+TypeSafeSet);
          }
}
输出:
The view of the Set is: [500, 900, 1100, 2200] 

示例3

import java.util.*;
public class CollectionsCheckedSetExample3 {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
            set = Collections.checkedSet(set, Integer.class);
            set.add(1500);
            set.add(1100);
            set.add(1800);
            System.out.println("Dynamic type safe view of Set is: "+set);
            Set set2 = set;
            set2.add("lidihuo");
            System.out.println(set2);
          }
}
输出:
Dynamic type safe view of Set is: [1800, 1500, 1100]
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.CollectionCheckedSetExample3.main(CollectionCheckedSetExample3.java:12)

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4