Java Vector

In this tutorial, you will learn about vector and its' implementation with example.

Java Vector

In this tutorial, you will learn about vector and its' implementation with example.

Vector is alike to ArrayList , it is also dynamic in nature means it's size increase with the increment in inserting element. But it also have some dissimilarities with ArrayList , which are given below :

  • Vector is synchronized 

  • Vectors are still using methods which are legacy now and these methods are not part of collections framework.

Vector class offers four constructors which are given below :

(1) The first constructor create a default size vector of initial size 10. Syntax is given below :


(2) The second type of constructor create a vector  whose initial size can be defined by user. Syntax is below :

Vector(int size)

(3) The third type of constructor create a vector whose initial size and the increment is user defined. Syntax is given below :

Vector(int size, int increment)

     The increment of vector occurs when the size is full, it automatically increment the size defined by user(here through increment variable).

(4) The fourth type of vector create a vector which contains the element of passed collection as argument. Syntax is given below :

Vector(Collection c)

For complete list of method of vectors click here.


In the below example, you will see vector and different methods implementation on this vector.

import java.util.*;

public class VectorExample {
public static void main(String argds[]) {
// set the initial size 3 and increment 2
Vector vec = new Vector(3, 2);
System.out.println("Vector's initial size: " + vec.capacity());
System.out.println("Elements in vector: " + vec.size());
System.out.println("After adding four elements vector's size: "
+ vec.capacity());
System.out.println("Vector's First element: " + vec.firstElement());
System.out.println("Vector's Last element: " + vec.lastElement());
if (vec.contains(3))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration ve = vec.elements();
System.out.println("\nElements in vector:");
while (ve.hasMoreElements())
System.out.print(ve.nextElement() + " ");


Vector's initial size: 3
Elements in vector: 0
After adding four elements vector's size: 5
Vector's First element: 1
Vector's Last element: 4.3
Vector contains 3.

Elements in vector:
1 2 3 4.3

Download Source Code

Share on Google+Share on Google+

Java Vector

Posted on: August 3, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Java Vector  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image