Java Enumeration Interface and Vector Example

Enumeration interface is part of java.util package. An object that implements this interface generates a series of elements, one at a time. Successive calls to the nextElement() method return successive elements of the series.

Enumeration Interface Java SE

public interface Enumeration<E>
{
   //To check if this enumeration has more elements
   boolean hasMoreElements()

   //Returns the next element of this enumeration
   E nextElement()
}

The above methods of this interface are used to enumerate through the elements of a vector, the keys of the hashtable and the values of the hashtable.

Note: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

Let’s see Enumeration example using Vector.

Enumeration Example

package com.sneppets.java.util;

import java.util.Enumeration;
import java.util.Vector;

/**
 * Program to demonstrate Enumeration interface in java.util package
 * @author sneppets.com
 */
public class EnumerationExample {

	public static void main(String[] args)
	{
		Vector<String> lang = new Vector<String>();
		Enumeration<String> langen = null;
		
		lang.add("Java");
		lang.add("Golang");
		lang.add("Php");
		lang.add("Python");
		lang.add("Perl");
		
		langen = lang.elements();
		
		while (langen.hasMoreElements())
		{
			System.out.println(langen.nextElement());
		}		
	}
}

Output

Java
Golang
Php
Python
Perl

Related Posts

  • Iterator Interface and Example

Reference

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments