Core Java

Java Vector Class Example

In this article, we shall discuss Vector in Java and its usage and common methods.

1. What is a Vector

The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is usually as large as vector size and the vector’s storage increases in chunks the size of capacityIncrement.

As of Java 2, the Vector class was retrofitted to implement the List interface, making a member of the Java Collections Framework. Let us look at the Collections framework and where Vector fits in.

Java Vector - Collections
Fig 1. Collections

The above diagram shows the Collections framework and how ArrayList, Vector and LinkedList fit in.

2. Constructors in Vector

The Vector class has the below constructors:

  • Vector(): Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.
  • Vector( Collection <? extends E> c): Constructs a vector containing elements of the specified collection in the order they are returned by the collection’s iterator.
  • Vector (int initialCapacity): Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
  • Vector (int initialCapacity, int capacityIncrement): Constructs an empty vector with the specified initial capacity and capacity increment.

3. Methods in Vector

The Vector class has the below commonly used methods:

  • boolean add (E e): Appends the specified element to the end of this Vector
  • void add (int index, E element): Inserts the specified element at the specified position in this Vector
  • boolean addAll (Collection<? extends E> c): Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection’s Iterator
  • boolean addAll(int index, Collection c): Inserts all of the elements in the specified Collection into this Vector at the specified position
  • void addElement(E obj): Adds the specified component to the end of this vector, increasing its size by one
  • int capacity(): Returns the current capacity of this vector
  • void ensureCapacity(int minCapacity): Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument
  • void forEach(Consumer action): Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception
  • int indexOf(Object o): Returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element
  • boolean remove(Object o): Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged

3. Java Vector example

Let us now look at an example to see the usage of some of the commonly used methods.

VectorExample.java

import java.util.Vector;

public class VectorExample{
    public static void main(String args[]){
        // usage of default constructor. Initial size is set as 10
        Vector vec = new Vector();

        // capacity of vector
        System.out.println("Initial vector capacity: "+vec.capacity());

        for(int i=0; i<4; i++){
            // usage of method add(E e)
            vec.add("John");
            vec.add("Jason");
            vec.add(1);
        }
        // updated capacity of vector
        System.out.println("new vector capacity after adding elements: "+vec.capacity());
        System.out.println("vector vec is: "+vec);
        
        
        // remove element at index 1
        vec.remove(1);
        System.out.println("Updated vector: "+vec);
        
        // clear vector
        vec.clear();
        System.out.println("vector vec is: "+vec);
        System.out.println("new vector capacity: "+vec.capacity());
        
        // Vector with initial size as 5. 
        Vector vector1 = new Vector(5);
        vector1.add("John");
        vector1.add("Jack");
        vector1.add("Jason");
        vector1.add("Ryan");
        System.out.println("First and last elements are: "+ vector1.firstElement() + " " + vector1.lastElement());;
    }
}

A new vector is created using Vector() constructor. This sets the default capacity as 10. We then added some elements to the vector. You will notice that the vector size got incremented after the capacity is reached. Vector also has methods to check the first and last elements as shown in the example.

Executing the code would give the result as:

Initial vector capacity: 10
new vector capacity after adding elements: 20
vector vec is: [John, Jason, 1, John, Jason, 1, John, Jason, 1, John, Jason, 1]
Updated vector: [John, 1, John, Jason, 1, John, Jason, 1, John, Jason, 1]
vector vec is: []
new vector capacity: 20
First and last elements are: John Ryan

4. Vector vs ArrayList and LinkedList

In Fig.1 above, we notice that Vector, ArrayList, and LinkedList implement List interface. Like an array, components in a Vector can be accessed using an integer index. When the minimum default capacity is reached, Vector’s size doubles, while ArrayList grows by 50%. Also note that Vector is synchronized, while ArrayList and LinkedList are not. Hence, if a thread-safe implementation is not needed, it is recommended to use ArrayList instead of Vector. Let us see the time complexity of these objects

OperationLinkedListArrayListVector
RetrieveO(N)O(1)O(1)
Add elementO(1)O(N)O(N)
Remove elementO(1)O(N)O(N)
Complexity comparison

As we notice, a LinkedList works better for adding or removing an element, but not for retrieval. ArrayList and Vector have similar behavior except that Vector is synchronized.

5. Download the Source Code

Download
You can download the full source code of this example here: Java Vector Class Example

Venkat-Raman Nagarajan

Venkat works for a major IT firm in India and has more than a decade of experience working and managing Java projects for a banking client.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button