1. Introduction

The Vector class is a thread-safe implementation of a growable array of objects. It implements the java.util.List interface and is a member of the Java Collections Framework. While it’s similar to ArrayList, these classes have significant differences in their implementations.

In this tutorial, we’ll explore the Vector class and some of its most common operations and methods.

2. How Does Vector Work?

The Vector class is designed to function as a dynamic array that can expand or shrink according to the application’s needs. Thus, we can access the objects of the Vector using the indices. Additionally, it maintains the insertion order and stores duplicate elements.

Every Vector aims to enhance its storage handling by keeping track of both the capacity and the capacityIncrement. The capacity is nothing but the size of the Vector. The size of the Vector increases as we add elements to it. Therefore, *the capacity remains consistently equal to or greater than the Vector‘s size*.

Every time the length of a Vector reaches its capacity, the new length is calculated:

newLength = capacityIncrement == 0 ? currentSize * 2 : currentSize + capacityIncrement

Similar to ArrayList, the iterators of the Vector class are also fail-fast. It throws a ConcurrentModificationException if we try to modify the Vector while iterating over it. However, we can access the iterator’s add() or remove() methods to structurally modify the Vector.

3. How to Use Vector

Let’s see how to create a Vector and perform various operations on it.

3.1. Creating a Vector

We can create Vector instances using the constructor. There are four different types of Vector constructors.

The first is the default constructor, which creates an empty Vector with the initial capacity of 10 and a standard capacityIncrement of 0:

Vector<T> vector = new Vector<T>();

We can create an empty Vector by specifying its initial size (capacity). In this case, its capacityIncrement is also set to 0:

Vector<T> vector = new Vector<T>(int size);

There’s another constructor using which we can specify the initial capacity and capacityIncrement to create an empty Vector:

Vector<T> vector = new Vector<T>(int size, int capacityIncrement);

Finally, we can construct a Vector by passing another Collection to the constructor. The resultant Vector contains all the elements of the specified Collection:

Vector<T> vector = new Vector(Collection<T> collection);

3.2. Adding Elements to Vector

Let’s create a method that returns a Vector. We’ll use this method for future operations:

Vector<String> getVector() {
    Vector<String> vector = new Vector<String>();

    vector.add("Today");
    vector.add("is");
    vector.add("a");
    vector.add("great");
    vector.add("day!");

    return vector;
}

Here, we’ve created an empty Vector of Strings with a default constructor and added a few Strings.

Based on the needs, we can add elements at the end or a specific index to a Vector. For this, we can use the add() method which is overloaded to satisfy various needs.

Now, let’s add an element at a specific index to vector:

vector.add(2, "not"); // add "not" at index 2

assertEquals("not", vector.get(2)); // vector = [Today, is, not, a, great, day!]

Here, we use the add(int index, E element) method of the Vector class to add the Stringnot” at index 2. We should note that it shifts all the elements after the specified index to the right by one position. Thus, the Stringnot” is added between the Strings “is” and “a“.

Similarly, we can add all the elements of a Collection to a Vector using the method addAll(Collection c). Using this method, we can append all the elements of a collection to the end of the Vector in the same order as that of the Collection:

ArrayList<String> words = new ArrayList<>(Arrays.asList("Baeldung", "is", "cool!"));

vector.addAll(words);

assertEquals(9,  vector.size());
assertEquals("cool!", vector.get(8));

After the execution of the above code, if we print vector, we’ll get the following:

[Today, is, not, a, great, day!, Baeldung, is, cool!]

3.3. Updating Elements

We can use the set() method to update the elements of a Vector. The set() method replaces the element at the specified index with the new element while returning the replaced element. Consequently, it accepts two arguments – the index of the element to be replaced, and the new element:

Vector<String> vector = getVector();

assertEquals(5, vector.size());
vector.set(3, "good");
assertEquals("good", vector.get(3));

3.4. Removing Elements

We can use the remove() method to remove an element from a Vector. It has been overloaded according to various needs. As a result, we can remove a specific element or an element at a specific index, or all the elements of a Vector. Let’s see a few examples.

If we pass an object to the remove() method, the first occurrence of it is deleted:

Vector<String> vector = getVector();
assertEquals(5, vector.size());

vector.remove("a");
assertEquals(4, vector.size()); // vector = [Today, is, great, day!]

Similarly, if we now pass 2 to the remove() method above, it deletes the element, great, at index 2:

vector.remove(2);
assertEquals("day!", vector.get(2));

We should note that all the elements to the right of the deleted element shift to their left by one position. Moreover, the remove() method throws an ArrayIndexOutOfBoundsException if we provide the index beyond the range of the Vector, i.e., index < 0* or *index >= size().

Finally, let’s remove all the elements of vector:

vector.removeAll();
assertEquals(0, vector.size());

3.5. Getting an Element

We can use the get() method to get an element of the Vector at a particular index:

Vector<String> vector = getVector();

String fourthElement = vector.get(3);
assertEquals("great", fourthElement);

The get() method also throws an ArrayIndexOutOfBoundsException if we provide the index beyond the range of the Vector.

3.6. Iterating Through a Vector

We can iterate through a Vector in multiple ways. However, one of the most common ways is the for-each loop:

Vector<String> vector = getVector();

for(String string : vector) {
    System.out.println(string);
}

We can also use the forEach() method to iterate through a Vector, especially when we want to perform a certain action on each element:

Vector<String> vector = getVector();
vector.forEach(System.out::println);

4. When to Use Vector

The first and obvious use of Vector is when we need a growable collection of objects. If we’re unsure about the size of the growing collection, but we know how frequently we’ll add or remove the elements, then we may prefer to use a Vector. In such cases, we can set capacityIncrement according to the situation.

However, since Vector is synchronized, it’s preferable to use it in case of multithreaded applications. In the case of single-threaded applications, ArrayList works much faster compared to Vector. Moreover, we can synchronize ArrayList explicitly using Collections.synchronizedList().

5. Conclusion

In this article, we had a look at the Vector class in Java. We also explored how to create a Vector instance and how to add, find, or remove elements using different approaches.

As always, the source code for the article is available over on GitHub.