📜  Java中的集合 list() 方法和示例

📅  最后修改于: 2022-05-13 01:55:04.316000             🧑  作者: Mango

Java中的集合 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
            List arrlist = new ArrayList();
  
            // creating object of Vector
            Vector v = new Vector();
  
            // 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 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
            List arrlist = new ArrayList();
  
            // creating object of Vector
            Vector v = new Vector();
  
            // 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 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]