Vector Class with Example

The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. Vector is a synchronized dynamically growable array with efficient access by index.

Vector Example:


import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;

public class VectorExample {

 public static void main(String[] args) {

  Vector v = new Vector();

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

  v.add("Java");
  v.add("J2EE");
  v.add("Spring");
  v.add("Hibernate");
  v.add("Ajax");
  v.add("Struts");

  System.out.println("Vector Values: " + v);

  Enumeration e = v.elements();
  System.out.print("Vector Elements Using Enumaration:");
  while (e.hasMoreElements()) {
   System.out.print(e.nextElement() + " ");
  }
  System.out.println("");

  Iterator itr = v.iterator();
  System.out.print("Vector Elements Using Iterrator:");
  while (itr.hasNext()) {
   System.out.print(itr.next() + " ");
  }
  System.out.println("");

  ListIterator listItr = v.listIterator();
  System.out.print("Vector Elements Using ListIterrator:");
  while (listItr.hasNext()) {
   System.out.print(listItr.next() + " ");
  }
  System.out.println("");

  System.out.println("Second Value of Vector: " + v.get(2));

  // Remove element from the vector
  v.remove(3);
  System.out.println("Vecor Values After Remove: " + v);

 }

}
Output:
Initial Capacity :10
Vector Values: [Java, J2EE, Spring, Hibernate, Ajax, Struts]
Vector Elements Using Enumaration:Java J2EE Spring Hibernate Ajax Struts 
Vector Elements Using Iterrator:Java J2EE Spring Hibernate Ajax Struts 
Vector Elements Using ListIterrator:Java J2EE Spring Hibernate Ajax Struts 
Second Value of Vector: Spring
Vecor Values After Remove: [Java, J2EE, Spring, Ajax, Struts]

Search: