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


Java Collections list()用法及代碼示例


java.util.Collections類的list()方法用於返回一個數組列表,該列表包含按枚舉返回順序指定的枚舉返回的元素。此方法提供了返回枚舉的舊式API與需要集合的新API之間的互操作性。

用法:

public static ArrayList list(Enumeration e)

參數:此方法將枚舉e作為參數,為返回的數組列表提供元素。


返回值:此方法返回一個數組列表,其中包含指定枚舉返回的元素。

以下示例說明了list()方法

示例1:

// Java program to demonstrate 
// list() 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> arrlist = new ArrayList<String>(); 
  
            // creating object of Vector<String> 
            Vector<String> v = new Vector<String>(); 
  
            // Adding element to Vector v 
            v.add("A"); 
            v.add("B"); 
            v.add("C"); 
            v.add("D"); 
            v.add("E"); 
  
            // printing the list 
            System.out.println("Current list : " + arrlist); 
  
            // creating Enumeration 
            Enumeration<String> e = v.elements(); 
  
            // getting arrlist of specified Enumeration 
            // using list() method 
            arrlist = Collections.list(e); 
  
            // printing the arrlist 
            System.out.println("Returned list: " + arrlist); 
        } 
  
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
Current list : []
Returned list: [A, B, C, D, E]

示例2:

// Java program to demonstrate 
// list() method 
// for Integer value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
        try { 
  
            // creating object of List<String> 
            List<Integer> arrlist = new ArrayList<Integer>(); 
  
            // creating object of Vector<String> 
            Vector<Integer> v = new Vector<Integer>(); 
  
            // Adding element to Vector v 
            v.add(10); 
            v.add(20); 
            v.add(30); 
            v.add(40); 
            v.add(50); 
  
            // printing the list 
            System.out.println("Current list : " + arrlist); 
  
            // creating Enumeration 
            Enumeration<Integer> e = v.elements(); 
  
            // getting arrlist of specified Enumeration 
            // using list() method 
            arrlist = Collections.list(e); 
  
            // printing the arrlist 
            System.out.println("Returned list: "
                               + arrlist); 
        } 
  
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
Current list : []
Returned list: [10, 20, 30, 40, 50]


相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Collections list() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。