当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Collections checkedList()用法及代码示例


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

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

由于将null视为任何引用类型的值,因此只要后备列表允许,返回的列表就允许插入null元素。


用法:

public static  List
    checkedList(List list, Class type)

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

  • list –要为其返回动态类型安全视图的列表
  • type –列表可以容纳的元素的类型

返回值:此方法返回指定列表的动态类型安全视图

以下示例说明了checkedList()方法

示例1:

// Java program to demonstrate 
// checkedList() method 
// for String value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
        try { 
  
            // creating object of List<String> 
            List<String> arlst = new ArrayList<String>(); 
  
            // Adding element to arlst 
            arlst.add("A"); 
            arlst.add("B"); 
            arlst.add("C"); 
            arlst.add("TajMahal"); 
  
            // printing the arrlist 
            System.out.println("List: " + arlst); 
  
            // create typesafe view of the specified list 
            List<String> 
                tslst = Collections 
                            .checkedList(arlst, String.class); 
  
            // printing the arrlist after operation 
            System.out.println("Typesafe view of List: " + tslst); 
        } 
  
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
输出:
List: [A, B, C, TajMahal]
Typesafe view of List: [A, B, C, TajMahal]

示例2:

// Java program to demonstrate 
// checkedList() method 
// for Integer value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
  
        try { 
  
            // creating object of List<Integer> 
            List<Integer> arlst = new ArrayList<Integer>(); 
  
            // Adding element to arlst 
            arlst.add(20); 
            arlst.add(30); 
            arlst.add(40); 
            arlst.add(50); 
  
            // printing the arrlist 
            System.out.println("List: " + arlst); 
  
            // create typesafe view of the specified list 
            List<Integer> 
                tslst = Collections 
                            .checkedList(arlst, Integer.class); 
  
            // printing the arrlist after operation 
            System.out.println("Typesafe view of List: " + tslst); 
        } 
  
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
输出:
List: [20, 30, 40, 50]
Typesafe view of List: [20, 30, 40, 50]


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Collections checkedList() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。