Enumeration Interface Example

Enumeration Interface Example

Enumeration Interface Example: Enumeration interface is from java.util package. It was introduced with JDK 1.0. It is used by many data structures especially with legacy classes. The DS of JDK 1.0 are known as legacy classes. They are Stack, Vector, Hashtable and Properties.
Enumeration Interface Example

Enumeration Interface Example

In the above code, the elements() method of Vector returns an object of Enumeration. Following is the elements() method signature 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 not designed for generics. But the program executes fine.

How Enumeration works?

The Enumeration interface comes with two methods.

1. public abstract boolean hasMoreElements();
2. 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.

Enumeration Interface Example

The object obj1 is explicitly casted to String and used for comparison.

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.

4 thoughts on “Enumeration Interface Example

Leave a Reply

Your email address will not be published. Required fields are marked *