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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。