Skip to Content

Enumerate through a Vector using Java Enumeration Example

  1. /*
  2.   Enumerate through a Vector using Java Enumeration Example
  3.   This Java Example shows how to enumerate through elements of a Vector
  4.   using Java Enumeration.
  5. */
  6.  
  7. import java.util.Vector;
  8. import java.util.Enumeration;
  9.  
  10. public class EnumerateThroughVectorExample {
  11.  
  12.   public static void main(String[] args) {
  13.     //create a Vector object
  14.     Vector v = new Vector();
  15.    
  16.     //populate the Vector
  17.     v.add("One");
  18.     v.add("Two");
  19.     v.add("Three");
  20.     v.add("Four");
  21.    
  22.     //Get Enumeration of Vector's elements using elements() method
  23.     Enumeration e = v.elements();
  24.    
  25.     /*
  26.       Enumeration provides two methods to enumerate through the elements.
  27.       It's hasMoreElements method returns true if there are more elements to
  28.       enumerate through otherwise it returns false. Its nextElement method returns
  29.       the next element in enumeration.
  30.     */
  31.    
  32.     System.out.println("Elements of the Vector are : ");
  33.    
  34.     while(e.hasMoreElements())
  35.       System.out.println(e.nextElement());
  36.   }
  37. }
  38. /*
  39. Output would be
  40. Elements of the Vector are :
  41. One
  42. Two
  43. Three
  44. Four
  45. */

Advertisement: