Vector in Java

Vector in Java

Vector implements dynamic array. Now it is evident from its definition that its size grows automatically like in ArrayList.
Prior to Java 2 i.e. before the concept of Collection was derived, Vector was used as a dynamic array. With the release of Java 2, Vector was redesigned to implement AbstractList and extend List.
It is similar to ArrayList but not exaclty same. It is different from ArrayList in two ways, as listed below:

  1. Vector is synchronized, i.e. it is thread safe.
  2. It contains legacy methods that are not part of Collection. We’ll discuss about later in this tutorial.

Vector has four constructors, as listed below:

[table “” not found /]

A vector is initially created with some capacity, post it is occupied the size increases as required plus some extra room. This extra space added is to avoid the repetitive memory allocation. This is important because allocation are costly in terms of time. If the increment size is not defined then size is doubled each allocation cycle.

Vector defines these protected data members:

[table “” not found /]

Apart from the methods defined by Collection and List, Vector has defined several legacy method of its own. These legacy methods are as defined below:
[table “” not found /]

Let see an example to understand how size of vector grows:

package com.code2succeed.collection;

import java.util.Vector;
public class vector {
	public static void main(String[] args) {

		Vector vector=new Vector();
		System.out.println("Initial vector capacity "+vector.capacity());
		//Add seven elements i.e less than 10 elements
		System.out.println("vector capacity after adding 7 elements "+vector.capacity());
		// Add another five elements i.e. total elements more than 10
		System.out.println("vector capacity after adding total 12 elements "+vector.capacity());

		//Element at any given index
		System.out.println("Element at given index=2 is "+vector.elementAt(2));
		//Size of vector
		System.out.println("Size of given vector is: "+vector.size());
		//Check if given vector is empty
		System.out.println("Is given vector empty? "+vector.isEmpty());
		//Remove all the elements of given vector
		System.out.println("Is given vector empty? "+vector.isEmpty());


Initial vector capacity 10
vector capacity after adding 7 elements 10
vector capacity after adding total 12 elements 20
Element at given index=2 is 3
Size of given vector is: 12
Is given vector empty? false
Is given vector empty? true

In above example we can see that initial size of vector is 10 but as number of elements added exceeds the initial capacity, the increases to double the initial size.

Leave a Reply

Your email address will not be published. Required fields are marked *