Java中的集合checkedSet()方法及其示例

Java中的集合checkedSet()方法及其示例

java.util.Collections类的 checkedSet() 方法用于返回指定集合的动态类型安全视图。

如果指定的集合是可序列化的,则返回的集合将是可序列化的。

由于null被认为是任何引用类型的值,因此返回的集合允许在支持集合的情况下插入null元素。

语法:

public static  Set checkedSet(Set s, Class type)

参数: 此方法将以下参数作为参数

  • s: 要返回动态类型安全视图的集合
  • type: s允许持有的元素类型

返回值: 该方法返回指定集合的 动态类型安全视图

以下是说明checkedSet()方法的示例

示例1:

// 一个演示checkedSet()方法的Java程序
// 对于字符串值

import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
        try {
 
            // 创建Set<String>的对象
            Set<String> hset = new TreeSet<String>();
 
            // 向hmap中添加元素
            hset.add("Ram");
            hset.add("Gopal");
            hset.add("Verma");
 
            // 打印集合
            System.out.println("Set: " + hset);
 
            // 创建指定集合的类型安全视图
            Set<String>
                tsset = Collections
                            .checkedSet(hset, String.class);
 
            // 打印指定列表的类型安全视图
            System.out.println("Typesafe view of Set: "
                               + tsset);
        }
        catch (IllegalArgumentException e) {
 
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出:

Set: [Gopal, Ram, Verma]
Typesafe view of Set: [Gopal, Ram, Verma]

示例2:

//一个演示checkedSet()方法的Java程序
//对于整数值

import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
 
            //创建一个Set<Integer>对象
            Set<Integer> hset = new TreeSet<Integer>();
 
            //向hset中添加元素
            hset.add(20);
            hset.add(30);
            hset.add(40);
 
            //打印集合
            System.out.println("Set: " + hset);
 
            //创建指定集合的类型安全视图
            Set<Integer>tsset = Collections
                        .checkedSet(hset, Integer.class);
 
            //打印指定列表的类型安全视图
            System.out.println("Typesafe view of Set: "+ tsset);
        }
        catch (IllegalArgumentException e) {
 
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出:

Set: [20, 30, 40]
Typesafe view of Set: [20, 30, 40]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程