Skip to Content

Iterate through elements Java Vector using Iterator Example

  1. /*
  2.   Iterate through elements Java Vector using Iterator Example
  3.   This Java Example shows how to iterate through the elements of java
  4.   Vector object using Iterator.
  5. */
  6.  
  7. import java.util.Vector;
  8. import java.util.Iterator;
  9.  
  10. public class IterateThroughVectorUsingIteratorExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create Vector object
  15.     Vector v = new Vector();
  16.    
  17.     //Add elements to Vector
  18.     v.add("1");
  19.     v.add("2");
  20.     v.add("3");
  21.     v.add("4");
  22.     v.add("5");
  23.    
  24.     //get an Iterator object for Vector using iterator() method.
  25.     Iterator itr = v.iterator();
  26.    
  27.     //use hasNext() and next() methods of Iterator to iterate through the elements
  28.     System.out.println("Iterating through Vector elements...");
  29.     while(itr.hasNext())
  30.       System.out.println(itr.next());
  31.    
  32.   }
  33. }
  34.  
  35. /*
  36. Output would be
  37. Iterating through Vector elements...
  38. 1
  39. 2
  40. 3
  41. 4
  42. 5
  43. */