Enumerated Collection enumeration()

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()

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

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

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

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

More discussion on Enumeration interface is available.

Leave a Reply

Your email address will not be published. Required fields are marked *