Enumeration in java. How to use java.util.Enumeration interface

In this post, let us see what is interface and its uses. Enumeration interface supports a simple iteration over a object such as Vector, Hashtable. It generates a series of all elements of the object which can be traversed one at a time using nextElement method. Many number of classes such as Vector , Hashtable , Dictionary, ConcurrentHashMap , ZipFile , DriverManager have methods that return Enumeration objects.

Enumeration interface defines two methods necessary to iterate through the elements of a vector, hashtable (both keys and values) , etc . The two methods are as follows

1. boolean hasMoreElements() : To check if this enumeration object contains more elements. Returns true if it contains atleast one element , otherwise returns false

2. Object nextElement() : Returns the next element of this enumeration object . If no more elements exist, it throws NoSuchElementException
      Enumeration is particularly useful for data structures for which elements cannot be accessed by index (hashtable,vector , ..etc)

Some of example code using Enumeration
1. To print all elements of a vector using Enumeration :

// Using static method Collections.enumeration(Collection c) – Returns an enumeration over the specified collection

2. To print all request parameter names with values . The following code may be used in servlet , action class …

Uses of Interface java.util.Enumeration
  Lots of packages are there that use Enumeration . Some of the packages are given below.
       1. java.util , 2. java.util.concurrent, 3. java.util.jar , 4. javax.naming , 5. java.sql , 6. java.security , java.lang and more …

Now let us see some of the methods that returns Enumeration object are as follows.

Vector.elements() – Returns an enumeration of the elements of this vector.
Dictionary.elements() – Returns an enumeration of the values in this dictionary.
Hashtable.elements() – Returns an enumeration of the values in this hashtable.
Collections.enumeration(Collection c) – Returns an enumeration over the specified collection.
Hashtable.keys() – Returns an enumeration of the keys in this hashtable.
Properties.propertyNames() – Returns an enumeration of all the keys in this property list
ConcurrentHashMap.elements() – Returns an enumeration of the values in this table.
DriverManager.getDrivers() – Retrieves an Enumeration with all of the currently loaded JDBC drivers
and more …..

The StringTokenizer implements the java.util.Enumeration interface, which means that StringTokenizer also implements two more methods of Enumeration interface (hasMoreElements( ) , nextElement( )) for accessing elements. These methods are used to traverse among the string tokens separated by the delimiter.
Note : The functionality of this Enumerator interface is similar to Iterator interface.

//Sample code using Enumeration to iterate through Hashtable


You may also like

Leave a Reply

Be the First to Comment!