java.util.Collections类的enumeration()方法用于返回指定集合上的枚举。这提供了与需要枚举作为输入的旧式API的互操作性。
用法:
public static Enumeration enumeration(Collection c)
参数:此方法将集合c作为要返回其枚举的参数。
返回值:此方法返回指定集合的枚举。
以下示例说明了enumeration()方法
示例1:
// Java program to demonstrate
// enumeration() 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>();
// Adding elemnet to srclst
arrlist.add("Ram");
arrlist.add("Gopal");
arrlist.add("Verma");
// Print the list
System.out.println("List: " + arrlist);
// creating object of type Enumeration<String>
Enumeration<String> e = Collections.enumeration(arrlist);
// Print the Enumeration
System.out.println("\nEnumeration over list: ");
// print the enumeration
while (e.hasMoreElements())
System.out.println("Value is: " + e.nextElement());
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
catch (NoSuchElementException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
List: [Ram, Gopal, Verma] Enumeration over list: Value is: Ram Value is: Gopal Value is: Verma
示例2:
// Java program to demonstrate
// enumeration() 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> arrlist = new ArrayList<Integer>();
// Adding elemnet to srclst
arrlist.add(20);
arrlist.add(30);
arrlist.add(40);
// Print the list
System.out.println("List: " + arrlist);
// creating object of type Enumeration<Integer>
Enumeration<Integer> e = Collections.enumeration(arrlist);
// Print the Enumeration
System.out.println("\nEnumeration over list: ");
// print the enumeration
while (e.hasMoreElements())
System.out.println("Value is: " + e.nextElement());
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
catch (NoSuchElementException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
List: [20, 30, 40] Enumeration over list: Value is: 20 Value is: 30 Value is: 40
相关用法
- Java Enumeration asIterator()用法及代码示例
- Java Enumeration hasMoreElements()用法及代码示例
- Java Enumeration nextElement()用法及代码示例
- Java Collections min()用法及代码示例
- Java Collections max()用法及代码示例
- Java Collections copy()用法及代码示例
- Java Collections checkedSortedSet()用法及代码示例
- Java Collections unmodifiableMap()用法及代码示例
- Java Collections unmodifiableList()用法及代码示例
- Java Collections checkedCollection()用法及代码示例
- Java Collections checkedList()用法及代码示例
- Java Collections checkedSet()用法及代码示例
- Java Collections checkedSortedMap()用法及代码示例
- Java Collections fill()用法及代码示例
- Java Collections synchronizedSortedSet()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Collections enumeration() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。