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,
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 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 |
5. 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 Articles:
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
- https://docs.oracle.com/javase/8/docs/api/java/util/List.html
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Enumeration.html
Happy Coding !!
Happy Learning !!