Thursday, 4 January 2018

Enumeration Iterator in Java

Tags

Enumeration Iterator is the first iterator present from JDK 1.0 and the rest of the iterators are included after the JDK 1.0 with additional functionalities. Enumeration Iterator is an interface used to get elements of legacy containers such as Hashtable and Vector.

Syntax:


Enumeration enumerate = vect.elements();
Here vect is the vector class object and enumerate is the type of Enumeration interface which refers to collection class object.

Methods available in Enumeration interface:

There are two methods present in the Enumeration Interface:
1. public boolean hasMoreElements(): This method is used to check if this enumeration has more elements.
2. public Object nextElement(): This method is used to retrieve the next element present in the collection.


If no more elements are present in the container then it will throw the NoSuchElementException.

Limitations of Enumeration Iterator:
1. Enumeration is only for legacy containers (Hashtable and Vector).
2. Enumeration iterator can't perform remove operations.
3. Only forward iteration is possible

EXAMPLE:

import java.util.*;

public class EnumerationIterator{

    public static void main(String args[]){

           Scanner in=new Scanner(System.in);

           Vector<String> vect=new Vector<String>();

           vect.addElement("Guru");
           vect.addElement("Tegh");
           vect.addElement("Bahadur");
           vect.addElement("Institute");
           vect.addElement("Of");
           vect.addElement("Technology");

           Enumeration enumerate=vect.elements();

           System.out.print("\n");

           while(enumerate.hasMoreElements()){

                 String s=(String)enumerate.nextElement();
                 System.out.println(s);
           }

           System.out.print("\n");
    }
}


OUTPUT:





EmoticonEmoticon