Thursday 19 January 2012

Enumeration Interface

Enumeration interface is from java.util package introduced with JDK 1.0 version, the starting version of Java. It is used by many data structures (especially with legacy classes) to print their values. Following program illustrates.
import java.util.*;
public class EnumerationDemo
{
    public static void main(String args[])
    {
        Vector vect1 = new Vector();
        vect1.addElement("Raju");  
        vect1.addElement("Reddy");
        vect1.addElement("Rao");
        vect1.addElement("Ratnakar");

        Enumeration e = vect1.elements();

        while(e.hasMoreElements())
        {
            Object obj1 = e.nextElement();
            System.out.println(obj1);
        }
    }
}
 


In the above code, the elements() method of Vector returns an object of Enumeration. Following is the elements() method signature as defined in Vector class.

public Enumeration elements();

Observe, the elements() method returns an object of Enumeration. The above program gives a warning as program is designed for generics. But the program executes fine.

How Enumeration works?

The Enumeration interface comes with two methods.

public abstract boolean hasMoreElements();
public abstract Object nextElement();

The Enumeration object e contains all the elements of the Vector vect1. The Enumeration object e maintains a cursor over the elements. By default, the cursor is placed on the first element. The hasMoreElements() returns true if the cursor points to an element else false. If there exists an element (known by the true value), the control enters the while loop. In the while loop, the nextElement() returns the value (pointed by the cursor) and then pushes to the next element. Again the loop goes back and checks whether an element exists or not (known by the return value of hasMoreElements()) and then enters the loop. The nextElement() does its job. Like this, complete elements of the e object are returned. When cursor points to no element, the hasMoreElements() method returns false and the loop terminates.

The nextElement() method returns an object of Object class. If required, it can be casted to the respective element and used in the program. The following modified while loop, adds "great man" if the name is Rao.

We can make an analogy for nextElement() method. It is like read() method of FileInputStream. The read() method reads and returns the byte where the file pointer exists and then pushes the file pointer to the next byte.

No comments:

Post a Comment