Enumeration Iterator

Enumeration Iterator In Java

It is an interface used to retrieve elements of legacy collections class like Vector and Hashtable. Enumeration is the primary iterator present from JDK 1.0 version, rests are included after that in JDK 1.2 with more functionality. Enumeration object create to calling elements() method of vector class on any vector object

 

// Suppose "vect" is an Vector class object. elm is of type Enumeration interface and refers to "vct"
    Enumeration elm = vct.elements();

 

In the Enumeration introduce the two methods.
 

// Tests if this enumeration contains more elements
public boolean hasMoreElements(); 

// Returns the next element of this enumeration
public Object nextElement();
 // It throws NoSuchElementException // if no more element present 

Example of Enumeration Iterator

// Java program to demonstrate Enumeration

import java.util.Enumeration;

import java.util.Vector;

public class TestEnumeration{

    public static void main(String[] args){

        // Create a vector and print its contents

        Vector vct = new Vector();

        for (int i = 0; i < 10; i++)

            v.addElement(i);

        System.out.println(vct);

        // At beginning e(cursor) will point to index just before the first element in vct

        Enumeration e = vct.elements();

        // Checking the next element availability

        while (e.hasMoreElements()){

            // moving cursor to next element

            int i = (Integer)e.nextElement();

            System.out.print(i + " ");
        }

    }

}

 

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9 

Limitations of Enumeration :

  • Enumeration is for legacy/Base classes(Vector, Hashtable) only. Hence it is not a universal iterator.
  • Remove operations can’t be performed using Enumeration.Enumeration didn't have remove method
  • Only forward direction iterating is possible by thee Enumeration.

Related Articles

post a comment