Collections enumeration() method in Java with Examples
Last Updated :
08 Jun, 2021
The enumeration() method of java.util.Collections class is used to return an enumeration over the specified collection. This provides interoperability with legacy APIs that require an enumeration as input.
Syntax:
public static Enumeration enumeration(Collection c)
Parameters: This method takes the collection c as a parameter for which an enumeration is to be returned.
Return Value: This method returns an enumeration over the specified collection.
Below are the examples to illustrate the enumeration() method
Example 1:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
List<String> arrlist = new ArrayList<String>();
arrlist.add( "Ram" );
arrlist.add( "Gopal" );
arrlist.add( "Verma" );
System.out.println( "List: " + arrlist);
Enumeration<String> e = Collections.enumeration(arrlist);
System.out.println( "\nEnumeration over list: " );
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);
}
}
}
|
Output:
List: [Ram, Gopal, Verma]
Enumeration over list:
Value is: Ram
Value is: Gopal
Value is: Verma
Example 2:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
List<Integer> arrlist = new ArrayList<Integer>();
arrlist.add( 20 );
arrlist.add( 30 );
arrlist.add( 40 );
System.out.println( "List: " + arrlist);
Enumeration<Integer> e = Collections.enumeration(arrlist);
System.out.println( "\nEnumeration over list: " );
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);
}
}
}
|
Output:
List: [20, 30, 40]
Enumeration over list:
Value is: 20
Value is: 30
Value is: 40
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...