Retrieving Elements from Collection in Java- EnumerationIterator


EnumerationIterator doesn’t have the option of eliminating elements from the collection, whereas an iterator has this facility. An additional disadvantage of using EnumerationIterator is that the name of methods associated with EnumerationIterator is difficult to remember.

Example

Following is an example −

 Live Demo

import java.util.Vector;
import java.util.Enumeration;
public class Demo {
   public static void main(String args[]) {
      Vector day_name = new Vector();
      day_name.add("Tuesday");
      day_name.add("Thursday");
      day_name.add("Saturday");
      day_name.add("Sunday");
      Enumeration my_days = day_name.elements();
      System.out.println("The values are ");
      while (my_days.hasMoreElements())
      System.out.println(my_days.nextElement());
   }
}

Output

The values are
Tuesday
Thursday
Saturday
Sunday

A class named Demo contains the main function, where a Vector instance is defined. Elements are added to the vector with the help of the ‘add’ function. Now, an Enumeration instance is created, and the vector is accessed and the function ‘elements’ is called on it. The output is printed on the screen by iterating over every element and checking if there are any more values in the vector.

Updated on: 14-Sep-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements