In this example, we are iterating a Vector using Enumeration. The steps are as follows:
1) Create a Vector object
2) Add elements to vector using add() method of Vector class.
3) Call elements() method to get the Enumeration of specified Vector
4) Use hashMoreElements() and nextElement() Methods of Enumeration to iterate through the Vector.
Example: Complete code
import java.util.Vector; import java.util.Enumeration; public class VectorEnumerationExample { public static void main(String[] args) { // Create a Vector Vector<String> vector = new Vector<String>(); // Add elements into Vector vector.add("Chaitanya"); vector.add("Shubham"); vector.add("Apoorv"); vector.add("Jin"); vector.add("Jacob"); // Get Enumeration of Vector elements Enumeration en = vector.elements(); /* Display Vector elements using hashMoreElements() * and nextElement() methods. */ System.out.println("Vector elements are: "); while(en.hasMoreElements()) System.out.println(en.nextElement()); } }
Output:
Vector elements are: Chaitanya Shubham Apoorv Jin Jacob
manda says
With JDK6 the below line from your code doesn’t get compiled
// Get Enumeration of Vector elements
Enumeration en = vector.elements();