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:
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
}
}
}
OUTPUTMonday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
DESCRIPTIONIn 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.