Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

Enumeration

The Enumeration is an interface in the java.util package.

java.util.Enumeration:

public interface java.util.Enumeration<E> {
public abstract booleanhasMoreElements();
public abstract E nextElement();
}

Important points of Enumeration:

1. Using Enumeration, we can traverse only legacy classes of the Collection Framework, such as java.util.Vector, java.util.HashTable, java.util.Properties, java.util.Stack, and java.util.Dictionary.
2. Through Enumeration, we can traverse the collection only in the forward direction.
3. We can perform add and remove operations on the collection while traversing it using Enumeration, and we will not encounter any exceptions, unlike with Iterator and ListIterator.

            
importjava.util.Enumeration;
importjava.util.Vector;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      Vectorvector = newVector();
      vector.add(101);
      vector.add("Hello");
      vector.add(12.34 f);
      vector.add(true);
      Enumerationenumeration = vector.elements();
      while (enumeration.hasMoreElements()) {
         System.out.println(enumeration.nextElement());
      }
      System.out.println("--------------------");
   }
}
    101
    Hello
    12.34
    true
    --------------------
            

In this example, we demonstrate how to create a java.util.Enumeration type object associated with a legacy type collection (in this case, we are using java.util.Vector).
Firstly, we construct a Vector and add some elements using the add method of the java.util.Vector class. Then, we create a java.util.Enumeration type object by invoking the elements() method of the java.util.Vector class.
Finally, we traverse the Vector using the hasMoreElements() and nextElement() methods.

Important Method of java.util.Enumeration interface:

1. public abstract booleanhasMoreElements(): It returns true when the current working enumeration has one more element to traverse; otherwise, it returns false.

2. public abstract Object nextElement(): This method returns the next element of the Enumeration and throws NoSuchElementException when there are no more elements in the current working Enumeration to traverse.