Enumerated Collection enumeration()

With legacy classes (JDK 1.0 DS) we use Enumeration. With collections framework classes we use Iterator or ListIterator. As such, with collection classes it is not possible to use Enumeration. To overcome this, the Collections class comes with enumeration() method. It returns collection class elements as an Enumeration. It is a good example on the interoperability between legacy and collection classes.

There are two methods on enumeration. One method returns an Enumeration object. The other takes as a parameter. The second method is illustrated in "Enumeration to ArrayList with list(Enumeration)".

  • static Enumeration enumeration(Collection col1): Returns an Enumeration object of Collection col1. With this method, the collection classes elements can be iterated with Enumeration.
Example on Enumerated Collection enumeration()
import java.util.*;
public class CollectionsEnumeration
{
  public static void main(String args[])
  {
    ArrayList firstList = new ArrayList();
    firstList.add(10);
    firstList.add("hello");
    firstList.add("world");
    firstList.add(true);
    firstList.add(10.5);
    System.out.println("firstList elements: " + firstList);

    Enumeration e = Collections.enumeration(firstList);

    System.out.print("\nfirstList elements using Enumeration: ");
    while(e.hasMoreElements())
    {
      Object obj = e.nextElement();
      System.out.print(obj + " ");
    }
  }
}


Enumerated Collection enumeration()
Output screenshot on Enumerated Collection enumeration()

     ArrayList firstList = new ArrayList();
     firstList.add(10);

A non-generics ArrayList object firstList is created. It is added with a few elements of different data types.

     Enumeration e = Collections.enumeration(firstList);

The enumeration(firstList) method of Collections class returns an Enumeration object e containing all the elements of firstList.

     while(e.hasMoreElements())
     {
       Object obj = e.nextElement();
       System.out.print(obj + " ");
     }

Using while() loop and methods hasMoreElements() and nextElement(), all the elements are printed.

More discussion on Enumeration interface is available.

Leave a Comment

Your email address will not be published.