Vector Class in Java with Examples, Declarations, Methods and Constructors

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

A vector is similar to a dynamic array whose size can be increased or decreased. Unlike arrays, it has no size limit and can store any number of elements. Since Java 1.2, it has been a part of the Java Collection framework. It's in the java.util package and implements the List interface, so we can use all of the List interface's methods here. Let us learn about Vector in Java Along with their declarations, constructors, methods and Examples.

Introduction

We all have used Array data structures in programming. In this article, we will learn about its competitor - Vector. So let’s get started.

Let’s look at the scenario of how vector in Java works. Say we have to build a tree data structure and store the value of the nodes.

Since we do not know the number of nodes in advance, we need an appropriate data structure that works for us. We could use Array, but we initialize it with a fixed size that cannot be changed in the future.

The problem arises when the Array becomes full, and we want to insert more nodes in the tree. Since Arrays cannot be expanded we need to look for another data structure whose size can be changed dynamically and Vectors come to our rescue.

What is Vector in Java?

  • Vector is a data structure that is used to store a collection of elements. Elements can be of all primitive types like int, float, Object, etc. Vectors are dynamic in nature and accordingly, grow or shrink as per the requirement.
  • Vector Class in Java is found in the java.util package.
  • Vector class is a child class of the AbstractList class and implements the List interface. Therefore we can use all the methods of the List interface.
  • Vectors are known to give ConcurrentModificationException when accessed concurrently at the time of modification.
  • When a Vector is created, it has a certain capacity to store elements that can be defined initially. This capacity is dynamic in nature and can be increased or decreased.
  • By definition, Vectors are synchronized, which implies that at a time, only one thread is able to access the code while other threads have to wait. Due to this, Vectors are slower in performance as they acquire a lock on a thread.

Declaration of Vector in Java

Syntax

  • Here, E denotes the Element Type
  • Vector Class extends AbstractList and implements multiple interfaces like Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess interfaces.
  • The directly known subclass is Stack.

Important points regarding the Increment of vector capacity

In each allocation cycle, Vector will expand in accordance with the increment if one is supplied. However, if the increment is left unspecified, each allocation cycle doubles the vector's capacity. Three protected data members are defined by Vector:

  • int capacityIncreament: Contains the value of the increment.
  • int elementCount: Number of elements that are currently stored in the vector.
  • Object elementData[]: The vector is kept in an array that is stored in it

Common Errors in the Declaration of Vectors

The following are typical mistakes made in the declaration of vectors:

  • If the InitialSize of the vector defined is negative, Vector throws an IllegalArgumentException.
  • It throws a NullPointerException if the specified collection is null.

Constructors in Vectors

  • Vector(): A default vector of capacity 10 gets created while calling this constructor.
  • Vector(int size): A vector is created with the given size as its capacity.
  • Vector(int size, int increment): A vector is created with the given size as its initial capacity, and whenever the capacity needs to be increased, it is increased by the given increment count.
  • Vector(Collection c): A Java vector is constructed from the given collection with the same order of elements as in the collection.

There are also three protected data members (Protected fields are the data members that can be accessed either within the class or from the derived class) in the Vector class.

  • int capacityIncreament: Contains the increment value.
  • int elementCount: Number of elements currently in vector stored in it.
  • Object elementData[]: Array that holds the vector is stored in it.

While initializing vectors in Java, one should keep in mind some exceptions that can occur:

  1. IllegalArgumentException: This is thrown if the initial size of the vector defined is negative.

  2. NullPointerException: This is thrown if the specified collection passed in the constructor is null.

Example: Initializing Java Vector Constructors

Output:

Explanation:

In the above code, we are performing the following steps:

  • Firstly, we made a defaultVector with an initial capacity of 10.
  • Then we created another vector, fixedSizeVector with Capacity = 100, and added 3 elements into it.
  • Then we created a third vector, incrementalVector with Capacity 30 and its capacity will increase by 20 whenever we want to add elements more than its capacity.
  • Then we create a vector, copyConstructorVector which is initialized from the elements of the fixedSizeVector.
  • Notice that the size of fixedSizeVector and capacity of copyConstructorVector is the same.
  • Then, we compare the capacity of all the vectors using the capacity() method.

Increment of Vector Capacity

By default, the vector increases its capacity by double. However, if an increment is specified in its constructor, Vector will grow in accordance with it in each allocation cycle.

Let’s take a look at the following example:

In the below code, we can see how the capacity() function is behaving:

Output:

Explanation:

In the above code, we are performing the following steps:

  1. We are making a vector called myVector with an initial capacity of 4 and a capacity increment value as 2. If the vector gets full and we try to add another element, the vector capacity will be increased by 2 every time.

  2. Then we are adding four elements in myVector. Now, we attempt to add one more element but since the vector gets full, its capacity increases by 2 and the new capacity is 6.

  3. Then we add two more elements making its capacity = 8 and size = 7.

Vector Methods in Java

The Java Vector class has a lot of methods that can be implemented depending on the use case. Following is the list of them:

Methods along with their argumentsUse case
add(E e)For appending the given element e in the given vector.
add(int index, E e)For inserting the given element, e, at the given index.
addAll(Collection c)For appending all the elements from collection c to the java vector.
addAll(int index, Collection c)For inserting all the elements present in the given collection c to the given java vector at the given index.
addElement(E e)For appending the element to the last of the vector. Keep in mind, this method increases the size of the vector by one.
capacity()For getting the length of the actual array inside the vector.
clear()For removing all of the elements from the given vector in java.
clone()For making a clone of the given vector in java.
contains(Object o)For finding if the given vector contains the specified element. It return true if element is found.
copyInto(Object[] objArray)For copying the elements of the given vector into the array passed in.
elementAt(int index)For accessing the element at the given index.
elements()For getting an enumeration of the components of the given vector in java.
equals(Object obj)For comparing and telling if the given object and the java Vector are equal or not.
firstElement()For getting the first object of the vector present at index 0.
get(int index)For getting the element at the given index from the Vector in java.
hashCode()For calculating the hash code value for the Vector in java.
indexOf(Object o)For finding out the index of the first occurrence of the specified element in this java vector. Keep in mind, if the element is not present, it will return -1.
insertElementAt(E element, int index)For inserting the given element at the index in this java vector.
isEmpty()For finding if the vector in java has any elements in it or not.
lastElement()For getting the last element.
lastIndexOf(Object o, int index)For finding the last occurrence of the given element and its corresponding index. It searches in reverse order and returns -1 if the element is not found in the vector.
remove(int index)For removing the element at the given position.
remove(Object o)For removing the first occurrence of the given element in this vector.
removeAll(Collection<?> c)For removing all the elements from the Vector that are present in the given Collection.
removeAllElements()For removing all the elements from this vector in java and set its size to zero.
removeElement(Object obj)For removing the first occurrence (going from the index 0) of the object from the vector.
removeElementAt(int index)For deleting the element at the given index from the vector in java.
removeIf(Predicate<? super E> filter)For removing all of the elements of this collection that satisfy the given predicate.
removeRange(int fromIndex,int toIndex)For removing all the elements from this vector whose index is between fromIndex, (inclusive), and toIndex, (exclusive).
replaceAll(UnaryOperator<E> operator)For replacing each element of this list with the result of applying the operator to that element.
retainAll(Collection<?> c)For deleting every element of vector except the ones that are contained in the given Collection.
set(int index, E element)For replacing the element at the given index with the given element.
setSize(int newSize)For setting the size of the given java vector to the size given.
size()For getting the number of elements in the java vector.
sort(Comparator<? super E> c)For sorting the vector according to the order induced by the Comparator.
subList(int fromIndex, int toIndex)This method returns a view of the portion of the vector between fromIndex and toIndex -1 (both inclusive).
toArray()For getting an array containing all of the elements in this java vector.
toArray(T[] a)For getting an array with all of the elements in this vector in the correct order. Here the runtime type of the returned array is that of the specified array.
toString()For getting a string representation of this Vector in Java, containing the String representation of each element.
trimToSize()For making the capacity of the vector in java to be equal to the vector’s current size.

Example

Java Program to Demonstrate Working of Vector :

Output:

Operations in Java Vectors

The most common operations include:

  • Adding elements to the vector.
  • Iterating over the elements we added in the vector.
  • Replacing elements at certain indexes in the vector.
  • Removing elements from the vector.

Adding elements

To add elements in any given vector, we can use add() method. This method can be implemented in different ways by overloading the method.

In the below code, we are performing the following steps:

  1. We have initialized a new vector, ourVector with a capacity 100
  2. Then we are two adding elements to it.

Output:

Iterating over the elements

Although there are many ways to iterate through the Vector, the most basic and widely used way is by using a basic for loop in combination with a get() method to get the element at the given index.

In the below code, we are performing the following steps:

  1. Here, we created a vector and added 2 elements, “a” and “b” .
  2. Then iterate over the vector with for loop and use the get() method to fetch those values.
  3. We can even use the for each loop to get the same output.

Output:

Replacing elements

Now let’s say we added a few elements, and we realize some of them need to be changed. This can be done using the set() method, and this takes an index as an argument and the new element which needs to be inserted at that index.

In the below code, we are performing the following steps:

  1. Here, we created a java vector and added 2 elements “happy” and “crying”.
  2. Then, using the set() method we replace the element at index 1 i.e “crying” with “laughing”.

Output:

Removing Elements

To remove any element from the vector in java, we can use the remove() method. This method can be implemented in 2 ways:

  • remove(Object): This simply removes the object from the Vector. If there are multiple instances of the object, then only the first occurrence of the object is removed.

  • remove(int index): This removes the element present at that specific index in the Vector. Do note that after removing the element from the vector, the vector fills the space by shifting all the elements to the left, and hence the indices of the elements are updated.

Output:

IMPORTANT:

Notice the way we have removed the Integer with value = 10 in the code snippet above. We cannot simply pass 10 as the argument of the remove function since it will interpret it as an index, not an element.

Conclusion

In this article, we mainly focused on the following:

  • The usage of vectors in java is mainly in cases when we want the processes in a synchronized manner since ArrayList and Vector both possess the property of dynamic sizes, but ArrayList is avoided when working with multiple threads.
  • Vector class in Java throws ConcurrentModificationException, IllegalArgumentException and NullPointerException exceptions.
  • Vectors in Java can be initialized using four types of constructors.
  • Various methods are provided in the Vector class for handling the vector operations.
  • We can use vectors to implement Tree Data structure or anywhere we are unsure about the size.