Java Collections checkedSet()

checkedSet() 用于获取指定Set的动态类型安全视图。

1 语法

public static <E> Set<E> checkedSet(Set<E> s, Class<E> type)  

2 参数

s:返回动态类型安全视图的集合。

type:允许s保留的元素类型。

3 返回值

返回指定Set的动态类型安全视图。

4 Collections checkedSet()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.checkedSet的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        TreeSet<String> set = new TreeSet<String>();
        //Insert values in the Set
        set.add("yiidain");
        set.add("baidu");
        set.add("google");
        set.add("renren");
        //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: [baidu, google, renren, yiidain]

5 Collections checkedSet()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.checkedSet的例子
 */
import java.util.*;

public class Demo {

    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]

6 Collections checkedSet()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.checkedSet的例子
 */
import java.util.*;

public class Demo {

    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("Yiidian");
        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.util.Collections$CheckedCollection.typeCheck(Collections.java:3037)
	at java.util.Collections$CheckedCollection.add(Collections.java:3080)
	at com.yiidian.Demo.main(Demo.java:21)

 

热门文章

优秀文章