Enumeration interface

In this article, we will discuss Enumeration interface in detail.

Key points about Enumeration:

  • Enumeration is a legacy interface
  • introduced in Java 1.0 version

Enumeration interface:

  • Enumeration interface allows to read or get element/object one-by-one from collection object
  • This interface is part of legacy collection
  • Only legacy collection classes like Vector or Properties or Hashtable are allowed to iterate over collection objects using Enumeration interface
  • Present in java.util package

How to get Enumeration object ?

  • We can create Enumeration object using elements() method present in all legacy classes
  • Legacy classes: Hashtable, Vector, Stack, Properties classes and Dictionary abstract class
  • For example,
    Vector v = new Vector();
    Enumeration e = v.elements(); // v is a legacy class Vector
    

Limitation of Enumeration interface:

  • Enumeration interface applicable only for legacy classes like Vector, Properties or Hashtable
  • all classes part of Java 1.0 version
  • It cannot be used with new collection framework classes like ArrayList or TreeSet (introduced in Java 1.2)
  • By enumerating, we can only read collection objects
  • but no other operations can be performed like remove element from collection object

Enumeration interface methods:

Enumeration methods Description
boolean hasMoreElements(); returns true, if there are more element\objects to be enumerated

otherwise returns false, if enumeration reaches end of collection

Object nextElement(); returns next Object in the enumeration

Enumeration examples:

EnumerationExample.java

package in.bench.resources.java.collection;

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

public class EnumerationExample {

	public static void main(String[] args) {

		// creating Vector object of type String
		Vector<String> vec = new Vector<String>();

		// adding elements to Vector object
		vec.addElement("Sundar Pichai");
		vec.addElement("Satya Nadella");  
		vec.addElement("Shiv Nadar");  
		vec.addElement("Shantanu Narayen");
		vec.addElement("Francisco D’Souza");

		// creating enumeration reference
		Enumeration<String> ceo = vec.elements();

		// enumerating using while loop
		while (ceo.hasMoreElements()){
			System.out.println(ceo.nextElement()); 
		}
	}
}

Output:

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Francisco D’Souza

Related Post:

 

References:

 

Happy Coding !!
Happy Learning !!

Iterator interface
Stack class