Java 集合 checkedCollection() 方法



描述

Java 集合 checkedCollection(Collection<E>, Class<E>) 方法用於獲取指定集合的動態型別安全檢視。

宣告

以下是 java.util.Collections.checkedCollection() 方法的宣告。

public static <E> Collection<E> checkedCollection(Collection<E> c,Class<E> type)

引數

  • c − 這是要返回動態型別安全檢視的集合。

  • type − 這是 c 允許儲存的元素型別。

返回值

方法呼叫返回指定集合的動態型別安全檢視。

異常

獲取整數集合的型別安全檢視示例

以下示例演示了 Java 集合 checkedCollection(Collection,Class ) 方法的使用,以獲取整數集合的型別安全檢視。我們建立了一個包含一些整數的 List 物件,並列印了原始列表。使用 checkedCollection(Collection, Integer) 方法,我們獲得了 Integer 的集合,然後列印它。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));

      System.out.println("Initial collection value: " + list);

      Collection<Integer> safeList = Collections.checkedCollection(list, Integer.class);
      System.out.println("Typesafe View: "+safeList);
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果。

Initial collection value: [1, 2, 3, 4, 5]
Typesafe View: [1, 2, 3, 4, 5]

獲取字串集合的型別安全檢視示例

以下示例演示了 Java 集合 checkedCollection(Collection,Class ) 方法的使用,以獲取字串集合的型別安全檢視。我們建立了一個包含一些字串的 List 物件,並列印了原始列表。使用 checkedCollection(Collection, String) 方法,我們獲得了 String 的集合,然後列印它。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<String> list = new ArrayList<>(Arrays.asList("Welcome","to","Tutorialspoint"));

      System.out.println("Initial collection value: " + list);

      Collection<String> safeList = Collections.checkedCollection(list, String.class);
      System.out.println("Typesafe View: "+safeList);
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果。

Initial collection value: [Welcome, to, Tutorialspoint]
Typesafe View: [Welcome, to, Tutorialspoint]
java_util_collections.htm
廣告