Vector Class in Java With Program Example

Share

Vector is a collection class that implements dynamic array data structure to store elements, signifying growable array as its underlying data structure.  It accepts duplicate elements and preserves insertion order. It can hold elements of different data types and allows null value. The Vector class was introduced in Java 1.2 version and is part of the original Java API.

It is similar to ArrayList, but is synchronized  and supports legacy methods which duplicates the behaviour of methods defined by Collection Framework.  It implements Serializable and RandomAccess interface. Its most of the methods are thread safe.

It is a legacy class and fully compatible with Collection, meaning one can use enhanced for loops to iterate through its elements.

Points to Remember

1) Its underlying data structure is dynamic array. It has the capability to grow or shrink as required. Like array, it uses zero  based index to access, add, delete, and update an element.

2) It is a legacy class, as a result, it supports legacy methods along with predefined methods by Collection framework. Further, it is synchronized.

3) It preserves insertion order that signifies all elements get stored in same order in which they inserted

4)  It can be used where multiple threads require to perform operations on same list. However, it can impact performance inversely, since, it’s synchronized.

Vector class provides various methods for adding, removing, searching and fetching elements. For example, one can use the addElement() method to add an element to the end of the vector, or the removeElement() method to remove an element. The elementAt() method can be used to retrieve an element at a specific index, and the indexOf() method can be used to find an element within the vector.
Further, it supports other methods such as trimToSize() and ensureCapacity(). The trimToSize() method reduces the capacity of a vector to the current number of elements, freeing up any unused memory, while the ensureCapacity() method increases the capacity.

Constructors of Vector

1. Vector v = new Vector();

The default constructor that creates the list with initial capacity of 10.

When vector crosses its capacity, a new vector object is created by the compiler and the values of first vector object is copied to new one. Lastly, reference variable starts pointing to new one and old reference becomes eligible for garbage collection.

How to calculate the capacity of vector?

capacity of new vector = 2 * current capacity

2. Vector v = new Vector(int capacity);

The constructor creates a vector with the given capacity provided in parameter.

3. Vector v = new Vector(int initialCapacity, int incrementalCapacity);

It creates a vector with initial capacity provided in the parameter. The incrementalCapacity specifies the new incremental capacity every time when the list resized  to be allocated .

4.Vector v = new Vector(Collection obj);

It creates equivalent list similar to the collection object provided in the constructor.

Methods in Vector

The Vector class in Java provides a number of methods for adding, removing, and manipulating elements within the vector. Here are some of the most commonly used methods:
  • addElement(Object obj): Insert an element to the end of the list.
  • removeElement(Object obj): Removes the very first occurrence of the given element
  • insertElementAt(Object obj, int indx): Inserts the given element at the specified position, moving elements greater than that index by 1.
  • removeElementAt(int indx): Deletes the element at the specified index.
  • setElementAt(Object obj, int indx): Replaces the element at the specified position with the specified element.
  • elementAt(int indx): Returns the element at the given position.
  • firstElement(): Returns the first element in the list.
  • lastElement(): Returns the last element in the list.
  • copyInto(Object[] o):  Copies elements to the given arrays passed as parameter.
  • indexOf(Object o): Returns the index of the first occurrence of the specified element.
  • trimToSize(): Reduces the capacity of the given vector to the current size.
  • ensureCapacity(int minCapacity): Increases the capacity to ensure that the list can hold at least the specified number of elements.
  • setSize() : Set the size of the given vector, storing null values to new empty spaces.
  • capacity(): Returns the current capacity of the vector.
These are some of the most commonly used methods of specific to Vector class in Java.
Also, the class supports other methods of List And Collection Interface.
MethodExplanation
add(T obj)It inserts an element to the end and returns true if the element is added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatiable collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear() It removes or truncates all the elements from the given list
contains(Object obj) It returns true if the given object is present within the list
containsAll(Collection obj) It returns true if all the elements in the given collection are present in the list
equal(Object obj) It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It check whether a list contains any element or not.
iterator() It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator() It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator
spliIterator()It returns SplitIterator object
subList(int from, int to) It returns sublist that falls between fromIndx and toIndex
toArray() It converts and returns an array corresponding to the given list

Disadvantages of using Vector Class

There are several disadvantages of using the Vector class in Java:
  1. Performance: The synchronization of the Vector class can slow down the performance of an application, as multiple threads accessing the same list would require to wait for each other to complete their operations. This can result in slower performance compared to an ArrayList
  2. Memory Overhead: The synchronization also result in additional memory overhead, as each element must maintain information about the locks used for synchronization.
  3. Legacy Class: The Vector class is a legacy class, introduced in Java 1.2 version , and has since been surpassed by more modern collection classes such as the ArrayList  that may have more features and are optimized.

Sandeep Verma

Published by
Sandeep Verma
Tags: collection collection framework Contructor of Vector java java program Legacy class List interface Methods of Vector Vector class