by Dinesh Thakur

The Vector class provides the capability to implement a growable array. The array grows larger as more elements are added to it. The array may also be reduced in size, after some of its elements have been deleted. This is accomplished using the trimToSize() method.

Vector operates by creating an initial storage capacity and then adding to this capacity as needed. It grows by an increment defined by the increment variable. The initial storage capacity and increment can be specified in Vector's constructor. There

are three types of constructors:


Vector(int size)

Vector(int size, int increment)

The increment specifies the number of elements to allocate each time the vector is filled up to its capacity. In default constructor we don't specify the initial capacity nor the increment so, it creates a default vector of initial size of 10.

All the vectors are created with an initial storage capacity and objects are added to them. When the initial capacity is filled and we attempt to store more objects in the vector, the vector allocates the space equal to that specified by increment. The increment is so selected that it allocates space to the new objects and still has some extra space. Specifying more space reduces the overhead of allocating space every time. If we don't specify the increment, the vector size is doubled every time its capacity is filled

import java.util.Vector;

import java.util.Enumeration;
class VectorsJavaExample
         public static void main(String args[])
             Vector vector = new Vector(3,2);
             vector.addElement(new Integer(15));
             vector.addElement(new Integer(12));
             vector.addElement(new Integer(25));
             vector.addElement(new Integer(25));
             vector.addElement(new Integer(10));
             System.out.println("First Element is: " + (Integer)vector.firstElement());
             System.out.println("Last Element is: "  + (Integer)vector.lastElement());
             Enumeration Enum = vector.elements();
             System.out.print("Total Elements in Vector are : ");
             System.out.print(Enum.nextElement() + " ");