Saturday, January 9, 2010

Enumeration

Categories: , ,

public interface Enumeration

An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.

For example, to print all elements of a vector v:

for (Enumeration e = v.elements() ; e.hasMoreElements() ;) {
System.out.println(e.nextElement());

}

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

NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

Two methods Enumeration
1.public boolean hasMoreElements()
Tests if this enumeration contains more elements.
Returns: true if and only if this enumeration object contains at least one more element to provide; false otherwise.

2.public Object nextElement()
Returns the next element of this enumeration if this enumeration object has at least one more element to provide.
Returns:the next element of this enumeration.
Throws: NoSuchElementException - if no more elements exist.

Example:

/*
Enumerate through a Vector using Java Enumeration Example
This Java Example shows how to enumerate through elements of a Vector
using Java Enumeration.
*/

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

public class EnumerateThroughVectorExample {

public static void main(String[] args) {
//create a Vector object
Vector v = new Vector();

//populate the Vector
v.add("One");
v.add("Two");
v.add("Three");
v.add("Four");

//Get Enumeration of Vector's elements using elements() method
Enumeration e = v.elements();

/*
Enumeration provides two methods to enumerate through the elements.
It's hasMoreElements method returns true if there are more elements to
enumerate through otherwise it returns false. Its nextElement method returns
the next element in enumeration.
*/

System.out.println("Elements of the Vector are : ");

while(e.hasMoreElements())
System.out.println(e.nextElement());
}
}
/*
Output would be
Elements of the Vector are :
One
Two
Three
Four
*/

Spread The Love, Share Our Article

Related Posts

No Response to "Enumeration"

Post a Comment