Java – Enumeration interface with example

In this article, we will discuss Enumeration interface in detail

1. Key points about Enumeration:

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

2. 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

Q) 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,
1
2
Vector v = new Vector();
Enumeration e = v.elements(); // v is a legacy class Vector

3. 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

4. Enumeration interface methods:

Enumeration methodsDescription
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

5. Enumeration examples:

EnumerationExample.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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:

1
2
3
4
5
Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Francisco D’Souza

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Iterator interface with example
Java - Stack class