Vector in Java

Understand Java's Vector class: its legacy synchronized design, how it differs from ArrayList, and why modern code should avoid it.

Vector<E> is one of Java's original collection classes, introduced in Java 1.0 before the Collections Framework existed. Like ArrayList, it implements a resizable array backed by an Object[]. Unlike ArrayList, every public method in Vector is synchronized, which means only one thread can call any method at a time. This blanket synchronisation made Vector thread-safe by default in the early days of Java multithreading, but it comes with a performance cost that is unnecessary in single-threaded contexts and insufficient for most multi-threaded ones. Vector is considered a legacy class and should not be used in new code.

Internal Structure and Behaviour

Vector stores elements in a Object[] called elementData. It also has a capacityIncrement field: when the array is full, Vector grows by capacityIncrement if it is greater than zero, or doubles in size otherwise (a 2× growth factor, compared to ArrayList's 1.5×). All public methods carry the synchronized keyword, making each method call acquire the intrinsic lock on the Vector instance.

Time Complexities

Operation Complexity Notes
get(i) O(1) Direct array lookup (synchronised)
add(e) (at end) Amortized O(1) O(n) on resize (doubles capacity)
add(i, e) (at index) O(n) Element shift + synchronised
remove(i) O(n) Element shift + synchronised
contains(o) O(n) Linear scan (synchronised)
size() O(1) Field read (synchronised)

Vector vs. ArrayList

Feature Vector ArrayList
Thread safety Synchronised (every method) Not synchronised
Growth factor 2× (doubles by default) 1.5×
Performance Slower (lock overhead) Faster (no locking)
Legacy status Yes (since Java 1.0) No (since Java 1.2)
Preferred for Nothing in new code General-purpose list
Concurrent alternative CopyOnWriteArrayList, Collections.synchronizedList —

Example 1: Basic Vector Usage (for understanding only)

import java.util.Vector;

public class VectorBasics {
    public static void main(String[] args) {
        Vector<String> v = new Vector<>(); // initial capacity 10, doubles on overflow

        v.add("Alpha");
        v.add("Beta");
        v.add("Gamma");
        v.add(1, "Delta"); // insert at index 1

        System.out.println(v);              // [Alpha, Delta, Beta, Gamma]
        System.out.println(v.get(0));       // Alpha
        System.out.println(v.size());       // 4
        System.out.println(v.capacity());   // 10 (Vector exposes capacity())

        v.remove("Beta");
        System.out.println(v);              // [Alpha, Delta, Gamma]

        // firstElement / lastElement (Vector-specific methods not in ArrayList)
        System.out.println(v.firstElement()); // Alpha
        System.out.println(v.lastElement());  // Gamma
    }
}

Example 2: Why Synchronisation on Vector Is Not Enough

import java.util.Vector;

// Demonstrates why per-method synchronisation is insufficient for compound operations
public class VectorCompoundRace {
    public static void main(String[] args) throws InterruptedException {
        Vector<Integer> v = new Vector<>();
        v.add(1);

        // Two threads doing "check-then-act" — still races even though Vector is synchronised
        Thread t1 = new Thread(() -> {
            // NOT atomic: size() and remove(0) are separately synchronised
            if (!v.isEmpty()) {
                // Another thread could remove the element between isEmpty() and remove(0)
                System.out.println("t1 removing: " + v.remove(0));
            }
        });
        Thread t2 = new Thread(() -> {
            if (!v.isEmpty()) {
                System.out.println("t2 removing: " + v.remove(0));
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // One thread will throw IndexOutOfBoundsException because the check
        // and the action are not a single atomic operation, despite Vector's sync.
    }
}

This example shows a classic pitfall: even though every Vector method is synchronised individually, compound operations (check-then-act, read-modify-write) are still subject to race conditions because the lock is released between method calls.

Common Mistakes

  • Using Vector in new code. The Java documentation marks Vector as legacy. Prefer ArrayList for single-threaded code and CopyOnWriteArrayList or Collections.synchronizedList(new ArrayList<>()) for thread-safe lists.
  • Assuming per-method synchronisation is sufficient for thread safety. Compound operations like "check if empty, then remove first" still race because the lock is released between the two method calls.
  • Confusing Vector's growth factor with ArrayList's. Vector doubles its capacity by default (2×); ArrayList grows by ~1.5×. If capacityIncrement is set on a Vector, it grows by that fixed amount instead.
  • Using the legacy Enumeration API. Vector.elements() returns an Enumeration, the predecessor to Iterator. Modern code should use Iterator or the for-each loop.
  • Iterating a Vector with Enumeration and expecting thread safety. Even though Vector synchronises its methods, iteration via Enumeration or Iterator can still see ConcurrentModificationException if another thread modifies the Vector during iteration.

Best Practices

  • Do not use Vector in new code. Use ArrayList (single-threaded) or CopyOnWriteArrayList / Collections.synchronizedList (multi-threaded).
  • If you encounter Vector in a legacy codebase, prefer replacing it with ArrayList after verifying thread-safety requirements.
  • For concurrent access, prefer java.util.concurrent classes over the legacy synchronised wrappers, as they offer better scalability with finer-grained locking or lock-free algorithms.
  • When you must interact with legacy Vector APIs, synchronise externally on the Vector instance for compound operations.
  • Understand Vector for interviews — it comes up frequently as a contrast to ArrayList.

Interview Questions

1. What is Vector in Java and why is it considered legacy?

Vector is a resizable-array List implementation from Java 1.0 where every public method is synchronized. It is considered legacy because it pre-dates the Collections Framework, its blanket synchronisation is expensive and often insufficient for real concurrent use cases, and modern alternatives (ArrayList, CopyOnWriteArrayList, ConcurrentHashMap) are available.

2. What is the difference between Vector and ArrayList?

Both are resizable-array implementations of List. Vector synchronises every method, making it thread-safe at the method level but slower. ArrayList is unsynchronised and faster. Vector also doubles its capacity on resize (2×), while ArrayList grows by ~1.5×. In new code, ArrayList is always preferred.

3. Is Vector truly thread-safe?

Per-method thread safety, yes — no two threads can execute a Vector method at the same time. But compound operations are still unsafe. For example, if (!v.isEmpty()) v.remove(0) is a race condition because another thread can empty the vector between the isEmpty() call and the remove() call. True compound-operation safety requires external synchronisation.

4. How does Vector's capacity growth differ from ArrayList?

Vector has a capacityIncrement field. If capacityIncrement > 0, the backing array grows by exactly that amount. If capacityIncrement == 0 (the default), the array doubles in size. ArrayList always grows by approximately 1.5× regardless of any parameter.

5. What should you use instead of Vector in modern Java?

For single-threaded code: ArrayList. For thread-safe reads with rare writes: CopyOnWriteArrayList. For fully concurrent read/write: Collections.synchronizedList(new ArrayList<>()) with external synchronisation for compound operations, or a ConcurrentLinkedQueue / BlockingQueue depending on the use case.

6. What legacy methods does Vector have that ArrayList does not?

Vector has firstElement(), lastElement(), elementAt(i), setElementAt(e, i), removeElementAt(i), insertElementAt(e, i), elements() (returns Enumeration), and capacity(). These pre-date the List interface and were the primary API before Java 1.2.

7. Why is Collections.synchronizedList preferred over Vector?

Collections.synchronizedList(list) wraps any List implementation (typically ArrayList) with per-method synchronisation, giving the same method-level safety as Vector but keeping the wrapped implementation swappable. It separates the synchronisation concern from the data-structure implementation, following better design principles.

Summary

  • Vector is a legacy, synchronised resizable-array List from Java 1.0; every method is synchronized.
  • Per-method synchronisation is insufficient for compound operations — races can still occur.
  • Vector doubles its capacity on overflow (2×) vs. ArrayList's ~1.5× growth.
  • Do not use Vector in new code; prefer ArrayList or CopyOnWriteArrayList.
  • Understanding Vector and its limitations is a common interview topic when discussing thread safety.

Continue Learning

Previous: LinkedList | Next: Stack

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.