< Prev
Next >

Vector Class

Vector is a legacy class through which we can construct a dynamic array. As legacy classes came out before the advent collection classes, so unlike collection classes, earlier version of Vector class did not provide iteration over its element in a for-each loop and we could neither get an Iterator to iterate over its elements.

But with the release of Collection Framework and JDK5, Vector class was updated to implement List and Iterable interface, so that it's possible to iterate over its elements in a for-each loop.


Vector class is similar to ArrayList in a way that Vector class is also used to store a collection of object, be it built-in objects or user-defined objects but with a difference.

Difference between ArrayList and Vector Class.

A simple constructor of Vector class

This constructor creates an empty Vector to hold a particular type of objects.
Example -
Vector <Integer> v = new Vector <Integer>();

This constructor creates a Vector to hold Integer objects.

Some legacy methods in Vector class.

Methods Description
int size() Returns the total number of elements in Vector.
boolean isEmpty() Returns true if Vector is empty.
E firstElement() Returns the first element in Vector.
E lastElement() Returns the last element in Vector.
E elementAt(int index) Returns the element present in Vector at a specified index.
void addElement(E element) Inserts an element in the Vector.
boolean contains(Object object) Returns true if the specified object is present in Vector.
boolean removeElementAt(int index) Returns true if element present in Vector is removed.

Vector class example

In this program we have created a Vector to hold String objects and we will add/remove and search elements from this Vector using its methods. Let's see the code now -:

import java.util.*;

class Vector1
public static void main(String... ar)
Vector<String> vec= new Vector<String>();


System.out.println("Vector = "+vec);

System.out.println("Size of Vector = "+ vec.size());

System.out.println("First element in Vector = "+vec.firstElement());
System.out.println("Last element in Vector = "+vec.lastElement());

System.out.println("Element at 2nd index = "+ vec.elementAt(2));


System.out.println("After removing element at 2nd index, Vector = "+ vec);


Output is :

Vector = [B, A, T, M, A, N]
Size of Vector = 6
First element in Vector = B
Last element in Vector = N
Element at 2nd index = T
After removing element at 2nd index, Vector = [B, A, M, A, N]

Program Analysis

Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter

< Prev
Next >
< LinkedHashMap
Stack Class >

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page