Menu
Topics Index
...
`


Collections Framework > Legacy Classes and Interfaces >
Siva Nookala - 20 Feb 2017
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Java Iterator.

Methods are provided to enumerate through the elements of a Java Vector, the keys of a Hashtable, and the values in a Hashtable. Enumerations are also used to specify the input streams to a SequenceInputStream.

Enumeration Methods:
MethodDescription
boolean hasMoreElements()Tests if this enumeration contains more elements.
Object nextElement()Returns the next element of this enumeration if this enumeration object has at least one more element to provide.

Enumeration
import java.util.Enumeration;
import java.util.Vector;

class EnumerationTest
{
    public static void main(String arg[])
    {
        Enumeration<String> days;
        Vector<String> dayNames = new Vector<String>();
        dayNames.add("Monday");
        dayNames.add("Tuesday");
        dayNames.add("Wednesday");
        dayNames.add("Thursday");
        dayNames.add("Friday");
        dayNames.add("Saturday");
        dayNames.add("Sunday");
        
        // Assigns vector elements to enumeration
        days = dayNames.elements();
        while (days.hasMoreElements()) { // LINE A
            System.out.println(days.nextElement()); // LINE B
        }    
    }
}
OUTPUT

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

DESCRIPTION

In this program, Enumeration object was assigned the Vector elements. At LINE A, it returns true if the enumeration has more elements or else returns false. At LINE B, it prints the next existing elements in the enumeration.

THINGS TO TRY
  • Take Enumeration object as year, Vector object as months and add the months from Jan to Dec and see the output.
  • Change the type from String to Integer and add integer marks as 75, 98, 85, 73 to vector and see the output.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App