Vector class in Java

The Vector class implements a growable array of objects. Just like an array, we can access its elements by using an integer index but the size of a Vector can grow or shrink as per our need.

Vector is now a part of the Collection framework since Java 1.2 and hence it implements the Collection interface along with some others as shown in the below image but it also contains some of the legacy methods from when it was not part of the collection framework.

Vector class structure
Some insights about Vector class
  • A Vector is synchronized but if the thread-safe environment is not needed, then it is recommended to use the ArrayList instead.
  • The Vector contains some of the legacy methods that are not part of the Collection framework.
  • Vector maintains the insertion order.
  • Iterators returned by the vector’s class iterator and listIterator are fail-fast. We will discuss the fail-fast iterators later in the post.
Things you should know about “Capacity” and “capacityIncrement” in Vector

Each vector tries to optimize the storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector’s size ( usually, it is greater than the vector’s size). The default capacity that is assigned to a vector at the time of the creation of an object is 10. So, in starting, if we don’t assign any capacity ourselves, then the size of a vector object is 0 while its capacity is 10.

Now, let’s talk about capacityIncrement. If the initial capacity is filled ( when the size of the vector is equal to the capacity assigned to it ), then we have to increase the capacity of the vector to accommodate more elements. But how do we know that how much capacity is to be increased? Here comes the capacityIncrement in the picture. If we don’t provide any value for the capacityIncrement or provided any value that is less than or equal to zero ( <=0 ), then the capacity of the vector would be doubled, otherwise, the capacity of the vector would be incremented by an amount defined by the capacityIncrement. Don’t worry we will look at it with an example afterward.

Declaration of Vector class

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

Constructors of the Vector class

There are four overloaded constructors of the Vector class, out of which one is the default constructor and three are the parameterized ones.

  • public Vector()
  • public Vector(int initialCapacity)
  • public Vector(int initialCapacity, int capacityIncrement)
  • public Vector(Collection c)

Now, we would only have to write the below line for making a vector object that will contain string elements using the default constructor.

Vector<String> v = new Vector<String>();

The default constructor will call the public Vector(int initialCapacity) with initialCapacity =10.

    public Vector() {
        this(10);
    }

Finally, the public Vector(int initialCapacity) will further call the public Vector(int initialCapacity, int capacityIncrement) constructor with capacityIncrement =0.

    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

In this way, an initial capacity of 10 will be assigned to the vector, even though the size of the vector is still zero. Below is the sample code to illustrate the same.

import java.util.Vector;

public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();
		
		System.out.println("Capcity of the vector:"+v.capacity());
		System.out.println("Size of the vector: "+v.size());
		

	}
}

Output –

Capcity of the vector:10
Size of the vector: 0

Add the elements into a vector

We can easily add elements to a vector using the add() method by just passing the element into its argument. Right now, we will just show you the implementation of add() method and will cover it in more detail in another post.

import java.util.Vector;

public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();
		
		v.add("first");  // appending the element at the end of the vector
		v.add("second"); 
		
		System.out.println("Vector: "+v.toString());
		
	}
}

Output –

Vector: [first, second]

And now let’s get back to the fail-fast iterators

Iterator is one of the many ways to iterate over a vector. The iterator returned by the vector class iterator and the listIterator methods is fail-fast. This means that if the vector is structurally modified after the iterator is created in any way except through the iterator’s own add or remove methods, then the iterator will throw a ConcurrentModificationException. Let’s show you this in action.

import java.util.Iterator;
import java.util.Vector;

public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();

		v.add("first"); // appending the element at the end of the vector
		v.add("second");

		Iterator<String> it = v.iterator();

		// iterating over the vector
		while (it.hasNext()) {
			System.out.println(it.next());
		}

		// adding the third element
		v.add("third");

		// Now, iterating over the vector will throw an exception
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output –

first
second
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.Vector$Itr.checkForComodification(Vector.java:1292)
	at java.base/java.util.Vector$Itr.next(Vector.java:1248)

Vector class methods

Method name What does it do?
public synchronized boolean add(E e) It appends the specified element to the end of the Vector.
public void add(int index, E element) It inserts the specified element at the specified position in the Vector.
public boolean addAll(Collection c) It appends all of the elements in the specified Collection to the end of the Vector.
public synchronized boolean addAll(int index, Collection c) It inserts all of the elements in the specified Collection into the Vector at the specified position.
public synchronized void addElement(E obj) It adds the specified component to the end of the vector.
public synchronized int capacity() It returns the current capacity of the vector.
public void clear() It removes all of the elements from the vector.
public synchronized Object clone() It returns the clone of the vector.
public boolean contains(Object o) It tells us whether the vector contains the specified element or not.
public synchronized boolean containsAll(Collection<?> c) It tells us whether the vector contains all of the elements of the specified collection or not.
public synchronized void copyInto(Object[] anArray) It copies the components of the vector into the specified array.
public synchronized E elementAt(int index) It returns the component at the specified index.
public Enumeration<E> elements() It returns an enumeration of the components of the vector.
public synchronized void ensureCapacity(int minCapacity) It increases the capacity of the vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
public synchronized E firstElement() It returns the first element of the vector.
public synchronized E get(int index) It returns the element at the specified position of the Vector.
public int indexOf(Object o) It returns the index of the first occurrence of the specified element.
public synchronized int indexOf(Object o, int index) It also returns the index of the first occurrence of the specified element starting from the index specified in the arguments.
public synchronized void insertElementAt(E obj, int index) It inserts the specified object as a component in this vector at the specified index.
public synchronized boolean isEmpty() It tells whether the vector has any components or not.
public synchronized E lastElement() It returns the last component of the vector.
public synchronized int lastIndexOf(Object o) It returns the index of the last occurrence of the specified element in the vector
public synchronized int lastIndexOf(Object o, int index) It returns the index of the last occurrence of the specified element in the vector, searching backwards from specified index passed in the arguments.
public synchronized E remove(int index) It removes the element at the specified position of the vector.
public boolean remove(Object o) It removes the first occurrence of the specified element in the vector.
public boolean removeAll(Collection<?> c)  It removes all of the elements present in the collection from the vector.
public synchronized void removeAllElements() It removes all components from the vector and sets its size to zero.
public synchronized boolean removeElement(Object obj) It removes the first occurrence of the object passed from the vector.
public synchronized void removeElementAt(int index) It deletes the component at the specified index.
public synchronized E set(int index, E element) It replaces the element at the specified position in the vector with the specified element.
public synchronized void setElementAt(E obj, int index) It sets the component at the specified index of the vector to be the specified object.
public synchronized void setSize(int newSize) It sets the size of the vector.
public synchronized int size() It returns the number of components in the vector.
public synchronized List<E> subList(int fromIndex, int toIndex) It returns a view of the portion of this List between fromIndex( inclusive ) and toIndex ( exclusive).
public synchronized Object[] toArray()  It returns an array containing all of the elements of the vector in the correct order.
public synchronized void trimToSize() It trims the capacity of the vector to be the vector’s current size.

Hope you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Related Articles
Liked the article? Share this on

Leave a Comment

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