Table of contents
1.
Introduction
2.
What is the Vector in Java?
2.1.
Declaration
3.
Constructors
4.
Methods
4.1.
Implementations
5.
Performing Multiple Operations on Vector in Java
5.1.
1. Add/Update elements
5.2.
2. Access elements
5.3.
3. Remove elements
5.4.
4. Iterating over elements
6.
Advantages of using Vector in Java
7.
Disadvantages of using Vector in Java
8.
Frequently Asked Questions
8.1.
What replaced Vector in Java?
8.2.
Is Java Vector still used?
8.3.
What are common errors one can encounter during the declaration of a vector?
8.4.
Is a Vector a class or interface in Java?
8.5.
What is the difference between Vector and ArrayList?
9.
Conclusion
Last Updated: Jun 28, 2025
Easy

Vector Class in Java

Author Yashesvinee V
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Vector class in Java helps create a dynamic array of objects and contains components that can be referenced using an index. They are very much similar to ArrayLists. The size of a Vector can change depending on whether elements are added or removed from it. The Vector class implements the List interface, which is used to define an ordered collection of elements. 

 Vector Class in Java

Now, let us learn about the functions/methods used to manipulate the size and contents of a vector.

Also see, Duck Number in Java and Hashcode Method in Java

What is the Vector in Java?

A Vector in Java is a synchronized, dynamic array that can grow or shrink in size as needed. It is part of the java.util package and implements the List interface. Unlike ArrayList, all methods in Vector are thread-safe, making it suitable for multithreaded environments, though it may have performance overhead due to synchronization.

Declaration

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

Constructors

Constructor SyntaxDescription
Vector<E> v = new Vector<E>();It constructs a default empty Vector with an initial capacity of ten.
Vector<E> v = new Vector<E>(int size);It constructs a Vector with a specified initial capacity.
Vector<E> v = new Vector<E>(int size, int incr);It constructs a Vector with a specified initial capacity and increment. It specifies the number of elements to be allocated each time a vector is resized.
Vector<E> v = new Vector<E>(Collection c);It creates a Vector with elements that are part of a Collection c.

Methods

MethodsDescription
add(int index, E element)It inserts the given element at the specified position in the vector. If the index is not specified, it appends the given element to the end of the vector.
addAll(int index, Collection c)It inserts all the elements of a specified collection into the vector, starting at the given position. If the index is not specified, it appends the elements of the given collection to the end of the vector.
addElement(E obj)It appends the given component to the end of the vector.
clear()It clears all the elements of the vector.
clone()It returns a shallow copy of the vector instance.
copyInto(Object[] arr)It copies the contents of the vector into the specified array.
contains(Object o)It returns true if the vector contains the specified element.
elementAt(int index)It returns the component at the given index.
firstElement()It returns the first element of the vector.
lastElement()It returns the last element of the vector.
forEach(Consumer action)It performs the given action for each element of the iterable until all elements have been processed or the action throws an exception.
get(int index)It returns the element at the specified position in the list.
indexOf(Object o)It returns the index of a given element in the list.
isEmpty()It returns true if the vector is empty.
iterator()It returns an iterator over the elements of the list in a proper sequence.
lastIndexOf(Object o)It returns the index of the last occurrence of a given element in the list, or -1 if it is not present.
listIterator()It returns a list iterator over the elements of the list in a proper sequence.
remove(int index)It removes the element present at the given index.
removeAll(Collection c)It removes all the elements which are also present in the given collection.
removeIf(Predicate filter)It removes the elements which satisfy the given predicate.
removeRange(int from, int to)It removes all the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
replaceAll(UnaryOperator operator)It replaces each element of the list with the result of applying the operator to that element.
retainAll(Collection c)It retains the elements of the vector that are contained in the Collection.
set(int index, E element)It replaces the element at the specified position with the given element.
size()It returns the number of elements in the list.
setSize(int newsize)It updates the size of the vector.
sort(Comparator c)It sorts the list according to the order mentioned by the specified comparator.
spliterator()A spliterator is an object used for traversing and partitioning elements of a source. This method creates a fail-fast spliterator over the elements of the vector.
subList(int from, int to)It returns a portion of the list between the specified fromIndex, inclusive, and toIndex, exclusive.
toString()It returns a string representation of the vector and its contents as well.
toArray()It returns an array of all the elements in the vector in proper sequence.
trimToSize()It trims the capacity of the vector instance to be the list's current size.

Implementations

The Vector class in Java provides a wide range of methods to manipulate and manage dynamic arrays. Here’s an example of how some commonly used methods are implemented and used:

import java.util.*;
import java.util.function.UnaryOperator;

public class VectorMethodsDemo {

    public static void main(String[] args) {
        // Creating a Vector
        Vector<String> vector = new Vector<>();

        // add() and addElement()
        vector.add("Apple");
        vector.addElement("Banana");
        vector.add(1, "Cherry");

        // addAll()
        List<String> moreFruits = List.of("Dates", "Elderberry");
        vector.addAll(moreFruits);

        // contains()
        System.out.println("Contains 'Banana'? " + vector.contains("Banana"));

        // elementAt(), firstElement(), lastElement()
        System.out.println("Element at index 1: " + vector.elementAt(1));
        System.out.println("First element: " + vector.firstElement());
        System.out.println("Last element: " + vector.lastElement());

        // get() and set()
        System.out.println("Element at index 2: " + vector.get(2));
        vector.set(2, "Blueberry");
        System.out.println("After setting index 2: " + vector.get(2));

        // indexOf() and lastIndexOf()
        vector.add("Apple");
        System.out.println("Index of 'Apple': " + vector.indexOf("Apple"));
        System.out.println("Last index of 'Apple': " + vector.lastIndexOf("Apple"));

        // isEmpty() and size()
        System.out.println("Is vector empty? " + vector.isEmpty());
        System.out.println("Vector size: " + vector.size());

        // clone()
        Vector<String> clonedVector = (Vector<String>) vector.clone();
        System.out.println("Cloned Vector: " + clonedVector);

        // iterator() and forEach()
        System.out.print("Vector elements using iterator: ");
        Iterator<String> it = vector.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();

        System.out.println("Vector elements using forEach:");
        vector.forEach(System.out::println);

        // remove() and removeIf()
        vector.remove(1); // Remove at index
        vector.removeIf(e -> e.startsWith("D")); // Remove if starts with "D"
        System.out.println("After removals: " + vector);

        // retainAll()
        vector.retainAll(List.of("Apple", "Blueberry"));
        System.out.println("After retainAll(): " + vector);

        // replaceAll()
        vector.replaceAll(String::toUpperCase);
        System.out.println("After replaceAll(): " + vector);

        // toArray()
        Object[] array = vector.toArray();
        System.out.println("Vector as Array: " + Arrays.toString(array));

        // sort()
        vector.sort(Comparator.naturalOrder());
        System.out.println("Sorted Vector: " + vector);

        // subList()
        vector.add("Zucchini");
        List<String> subList = vector.subList(0, 2);
        System.out.println("SubList (0 to 2): " + subList);

        // toString()
        System.out.println("Vector as String: " + vector.toString());

        // copyInto()
        String[] copyArray = new String[vector.size()];
        vector.copyInto(copyArray);
        System.out.println("Copied into Array: " + Arrays.toString(copyArray));

        // trimToSize()
        vector.trimToSize();
        System.out.println("After trimToSize(): Size = " + vector.size());

        // spliterator()
        System.out.println("Using spliterator:");
        Spliterator<String> spliterator = vector.spliterator();
        spliterator.forEachRemaining(System.out::println);

        // clear()
        vector.clear();
        System.out.println("Vector after clear(): " + vector);
    }
}
You can also try this code with Online Java Compiler
Run Code

Performing Multiple Operations on Vector in Java

1. Add/Update elements

import java.util.Vector;

public class Main {
    public static void main(String[] args) {
        Vector<String> alpha= new Vector<>();

        // Using the add() method
        alpha.add("A");
        alpha.add("B");

        System.out.println("Vector: " + alpha);

        Vector<String> alphanum = new Vector<>();
        alpha.add("1");
        
        alpha.addElement("2");

        alphanum.addAll(alpha);
        System.out.println("New Vector: " + alphanum);
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Vector: [A, B]
New Vector: [A, B, 1, 2]

2. Access elements

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Vector<String> alpha= new Vector<>();

        // Using the add() method
        alpha.add("A");
        alpha.add("B");
        alpha.add("C");
        alpha.add("D");
        alpha.add("E");
        System.out.println("First Element: " + alpha.firstElement());
        System.out.println("Element at index 2: " + alpha.elementAt(2));
        
        // Using Iterator
        Iterator<String> iterate = alpha.iterator();
        System.out.print("Vector: ");
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
      }
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

First Element: A
Element at index 2: C
Vector: A, B, C, D, E, 

3. Remove elements

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Vector<String> alpha= new Vector<>();

        // Using the add() method
        alpha.add("A");
        alpha.add("B");
        alpha.add("C");
        alpha.add("AD");
        alpha.add("E");
        System.out.println("Vector: " + alpha);
        
        System.out.println("Removing element at index 2: " + alpha.remove(2));
        
        System.out.println("Removing elements starting with A .. ");
        alpha.removeIf(e -> e.startsWith("A"));
        System.out.println("Vector: " + alpha);
    
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Vector: [A, B, C, AD, E]
Removing element at index 2: C
Removing elements starting with A ..
Vector: [B, E]
You can also try this code with Online Java Compiler
Run Code

4. Iterating over elements

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Vector<String> alpha = new Vector<>();

        // Adding elements to the Vector
        alpha.add("Java");
        alpha.add("Python");
        alpha.add("C++");
        alpha.add("JavaScript");

        // Using for-each loop
        System.out.print("Iterating using for-each loop: ");
        for (String lang : alpha) {
            System.out.print(lang + ", ");
        }

        // Using for loop
        System.out.print("\nIterating using for loop: ");
        for (int i = 0; i < alpha.size(); i++) {
            System.out.print(alpha.get(i) + ", ");
        }

        // Using ListIterator
        System.out.print("\nIterating using ListIterator: ");
        ListIterator<String> listIterator = alpha.listIterator();
        while (listIterator.hasNext()) {
            System.out.print(listIterator.next() + ", ");
        }

        // Using forEach() method with lambda
        System.out.print("\nIterating using forEach method: ");
        alpha.forEach(e -> System.out.print(e + ", "));
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Iterating using for-each loop: Java, Python, C++, JavaScript, 
Iterating using for loop: Java, Python, C++, JavaScript, 
Iterating using ListIterator: Java, Python, C++, JavaScript, 
Iterating using forEach method: Java, Python, C++, JavaScript, 

Advantages of using Vector in Java

  • Thread Safety: Vectors are synchronized, making them safe for use in multi-threaded environments without requiring external synchronization.
     
  • Dynamic Sizing: Vectors automatically resize themselves to accommodate more elements when the capacity is exceeded.
     
  • Legacy Support: Vector has been part of Java since its early versions, providing backward compatibility with older code.
     
  • Built-in Methods: Vectors offer a rich set of methods for adding, removing, and manipulating elements, making them easy to use in various scenarios.
     
  • Fail-Safe Iteration: Iterators for Vectors are fail-safe, meaning they operate over a cloned copy of the collection, avoiding concurrent modification exceptions.

Disadvantages of using Vector in Java

  • Performance Overhead: Due to synchronization, Vectors have higher performance overhead compared to unsynchronized collections like ArrayList.
     
  • Outdated: Vector is considered outdated and has been largely replaced by collections from the java.util.concurrent package and ArrayList for most use cases.
     
  • Memory Wastage: Vectors tend to over-allocate memory when resizing, leading to wasted memory if not properly managed.
     
  • Inefficient in Single-Threaded Applications: Since Vectors are synchronized, they can be slower and less efficient in single-threaded applications compared to alternatives like ArrayList.

Frequently Asked Questions

What replaced Vector in Java?

ArrayList replaced Vector in Java as it is faster and not synchronized by default, making it more efficient in single-threaded environments.

Is Java Vector still used?

Java Vector is still used in legacy systems, but it's generally avoided in new code due to its synchronized nature and lower performance than modern alternatives.

What are common errors one can encounter during the declaration of a vector?

If the size parameter of the vector constructor is passed a negative value, it throws an IllegalArgumentException. A NullPointerException is thrown when a null value is passed instead of a collection in the constructor.

Is a Vector a class or interface in Java?

Vector is a class in Java, part of the java.util package. It implements the List interface and provides a dynamic array that can grow as needed. Vector is synchronized, making it thread-safe but slower than non-synchronized alternatives.

What is the difference between Vector and ArrayList?

The main difference is that Vector is synchronized, making it thread-safe, while ArrayList is not. Due to this, Vector has more overhead and performs slower in single-threaded environments, whereas ArrayList offers better performance for non-threaded applications.

Conclusion

In this article, we explored the Vector class in Java, starting with its significance as a dynamic array in data structures. We looked its constructors, methods, and key operations. We also discussed the advantages and disadvantages of using Vectors, offering a comprehensive understanding of its application in Java.

Recommended Readings:

Live masterclass