當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。