Vector in Java

  • Vector class extends AbstractList and implements List interface.
  • Vector is dynamic array which can grow automatically according to the required size.
  • Vectors can hold only objects and not primitive types (eg: int,float,double etc). If you want to put a primitive type in a Vector, put it inside an object.
  • Vector value can get by Enumeration interface.
  • Vector is synchronized and hence thread – safe.
  • Vector can be used in multi – threaded environment.
  • The default size of vector is 10.
  • Vector provides basic operations such as addElement(), elementAt( ), firstElement( ), lastElement( ), indexOf( ), lastIndexOf( ), removeElement( ) and removeElementAt( ) method.
The following table demonstrates the constructors of the Vector class and its meaning.

Constructor
Meaning
Vector()
Constructs an empty vector.
Vector(Collection c)
Constructs a vector containing the elements of the given collection.
Vector(int capacity)
Constructs a vector with the given initial capacity.
Vector(int capacity, int incr)
Constructs a vector with the given initial capacity and incremental value

The following program shows a simple use of Vector.

Example:

/**
From SimpleVector.java
*/

import java.util.Vector;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleVector
{
    public static void main(String args[])
    {
        Vector v = new Vector();
        v.addElement("Item1");
        v.addElement("Item2");
        v.addElement("Item3");
        v.addElement("Item4");
        v.addElement("Item5");
        v.addElement("Item6");
        v.addElement("Item7");
        System.out.println("Size="+v.size());

        System.out.println("First Element="+v.firstElement());
        System.out.println("Last Element="+v.lastElement());
        System.out.println("The Vector elements are"+"\n"+v);
    }
}

Output:
Size=7
First Element=Item1
Last Element=Item7
The Vector elements are
[Item1, Item2, Item3, Item4, Item5, Item6, Item7]

The following program shows use of Vector with Enumeration Interface.

Example:

/**
From VectorwithEnumeration.java
*/

import java.util.Enumeration;
import java.util.Vector;

/**
 *
 * @author JavaHotSpot
 */

public class VectorwithEnumeration
{
 public static void main(String args[])
    {
        Vector v = new Vector();
        v.addElement("Item1");
        v.addElement("Item2");
        v.addElement("Item3");
        v.addElement("Item4");
        v.addElement("Item5");
        v.addElement("Item6");
        v.addElement("Item7");
        System.out.println("The Vector elements are");
        Enumeration em = v.elements();
        while(em.hasMoreElements())
        {
            System.out.println(em.nextElement());
        }
    }
}

Output:
The Vector elements are
Item1
Item2
Item3
Item4
Item5
Item6