Java Vector iterate using for each loop

Introduction

To iterate Vector using for each loop in Java

for (int i : v)
   System.out.print(i + " ");
      

Full source


import java.util.Vector;

public class Main {
  public static void main(String args[]) {

    // initial size is 3, increment is 2
    Vector<Integer> v = new Vector<Integer>(3, 2);

    System.out.println("Initial size: " + v.size());
    System.out.println("Initial capacity: " + v.capacity());

    v.addElement(1);//  w  w  w  .  j a va  2s  .  co  m
    v.addElement(2);
    v.addElement(3);
    v.addElement(4);

    // Use an enhanced for loop to display contents.
    System.out.println("\nElements in vector:");
    for (int i : v)
      System.out.print(i + " ");

  }
}



PreviousNext

Related