skip to content

How does Vector differ from ArrayList in Java, and why is Vector treated as a legacy class?

level: middleimportance: should knowfreq 62%

answer

  1. same array, different locks
  2. one call atomic, two calls not
  3. increment if positive, otherwise double
  4. docs leave ArrayList's growth unspecified
  5. legacy label, no @Deprecated

basics

~20 s

Vector is ArrayList's older, synchronized sibling: nearly every call takes its own lock, and it doubles when full or adds a fixed capacityIncrement. It predates the Collections Framework, ArrayList suits unshared lists, and per-call locks leave compound actions unsafe, hence legacy.

solid answer

~50 s

`Vector` and `ArrayList` are both array-backed `List`s with the same indexed-access and shifting costs. `Vector`, from Java 1.0, takes its own monitor on nearly every operation; `ArrayList`, from 1.2, takes no lock. When full, `Vector` adds `capacityIncrement` if that is positive and otherwise doubles, while the JDK's `ArrayList` adds half, a policy its docs leave unspecified. `Vector` is not deprecated, but the Collections Framework lists it under legacy implementations, and its Javadoc recommends `ArrayList` when thread safety isn't needed. When it is needed, per-call locks still don't make `if (!v.contains(x)) v.add(x)` or a traversal atomic, so you hold the lock yourself anyway. `Collections.synchronizedList` adds per-call locking on the wrapper to any list, though its iterators take no lock, so traversals still need `synchronized (list)`; `CopyOnWriteArrayList` suits lists that are traversed far more than they are changed.

code

java · 14 lines
java
import java.util.Vector;

public class VectorGrowth {
    public static void main(String[] args) {
        Vector<Integer> doubling = new Vector<>();     // capacity 10, increment 0
        Vector<Integer> stepped = new Vector<>(10, 3); // capacity 10, increment 3
        for (int i = 0; i < 11; i++) {
            doubling.add(i);
            stepped.add(i);
        }
        System.out.println(doubling.capacity()); // 20
        System.out.println(stepped.capacity());  // 13
    }
}

go deeper

for a junior

Recall the headline differences: Vector locks nearly every call and ArrayList locks none; Vector doubles by default and ArrayList grows by about half. Say that new code normally uses ArrayList and that Vector is old but not deprecated.

for a middle

Explain the growth rule including a positive capacityIncrement, and why fixed steps lose amortized constant appends. Show that each call is atomic while contains followed by add is not, and that synchronizing on the Vector fixes it because its methods lock on the instance.

for a senior

When you meet a Vector in old code, find out whether it is really shared before changing it, because ArrayList silently removes the locking. Look for subclasses using the protected fields and for traversals that never held the lock.

for a principal

The decision is how far to chase the legacy type. Rewriting every private Vector costs review time for little gain, so a rule against new uses, with shared ones fixed when that code next changes, is often the cheaper position. Public APIs exposing Vector are the expensive case.

## What the two classes share `Vector` and `ArrayList` are both **resizable arrays**: each keeps its elements in an internal `Object[]` and implements `List` and `RandomAccess`. The costs that follow from an array are therefore the same in both. Reading by index is constant time, and inserting or removing in the middle shifts every later element. The `ArrayList` Javadoc says it directly: the class is "roughly equivalent to `Vector`, except that it is unsynchronized." The real differences are locking, growth, the extra API and status. ## Side by side | Aspect | `Vector` | `ArrayList` | |---|---|---| | Since | Java 1.0, made a `List` in 1.2 | Java 1.2 | | Locking | Takes the instance's monitor on nearly every operation | None; callers synchronize externally if they share it | | When the array is full | Adds `capacityIncrement` if positive, otherwise doubles | Adds half in the JDK's code; the docs leave it unspecified | | `new` with no arguments | Allocates an array of 10 at once | Documented capacity 10; the JDK's code defers the array until the list first needs room | | Capacity visible? | Public `capacity()` | No public method | | Older methods | `addElement`, `elementAt`, `elements()` and more | None | | Out-of-range `get` | `ArrayIndexOutOfBoundsException` | `IndexOutOfBoundsException` | ## What the locking does and does not give Most public `Vector` methods are declared `synchronized`. Most others delegate to one that is, as `add(int, E)` does to `insertElementAt`, or lock a block inside, as `addAll(Collection)` does. The lock is the `Vector` instance, so a single call that holds it runs atomically. Readers wait for each other too, because `get` takes the same monitor. Atomic calls do not make **compound actions** atomic: - **Check then act:** in `if (!v.contains(x)) v.add(x);` the lock is released between the calls, so two threads can both add `x`. - **Size then index:** `v.get(v.size() - 1)` can throw if another thread shrinks the `Vector` between the calls. - **Traversal:** the iterator's `next()` locks for that one call and its `hasNext()` not at all, so another thread's `add` during a loop can cause `ConcurrentModificationException`. The fix is to hold the same monitor across the whole action: ```java synchronized (v) { if (!v.contains(x)) { v.add(x); } } ``` That works because the methods lock on the instance, and it exposes the problem: the code's safety now comes from the caller's lock, not the per-call locks, and a list used by one thread gains nothing from them. ## How capacity grows `Vector`'s rule is documented on `ensureCapacity`: the new capacity is the old one plus `capacityIncrement`, or twice the old one if the increment is zero or negative, and if that is still too small, exactly `minCapacity`. So `new Vector<>()` goes 10, 20, 40, and `new Vector<>(10, 3)` goes 10, 13, 16. `ArrayList` promises less. Its Javadoc says the growth policy is not specified beyond adding an element having constant amortized time cost. In the JDK's code the private `grow(int)` adds `oldCapacity >> 1`, giving 10, 15, 22, 33. Both private `grow` methods call the same internal helper, `ArraysSupport.newLength`, and the preferred step they pass is the main difference. A positive `capacityIncrement` is a trap for large lists. With a fixed step, the number of reallocations rises in proportion to the size and each one copies everything so far, so total copying becomes quadratic. Starting from capacity 10, 100,000 appends copy about 164,000 references when doubling and about 500 million with an increment of 10. ## Why it is treated as legacy `Vector` is **not deprecated**: the class carries no `@Deprecated`, so the compiler gives no deprecation warning. The label is a status, and several things produce it: - **The framework's own words.** Its outline lists `Vector` under "Legacy implementations", as a synchronized `List` "with additional legacy methods". - **The class's own advice.** "If a thread-safe implementation is not needed, it is recommended to use `ArrayList` in place of `Vector`." - **Redundant API.** `addElement` is identical in function to `add`, `elementAt` to `get`, and `insertElementAt(obj, index)` takes its arguments in the opposite order from `add(index, obj)`. - **Other tools for shared lists.** `Collections.synchronizedList` adds per-call locking to any list, taking the wrapper's lock, though its iterators and streams take none, so a traversal must hold `synchronized (list)` itself. `CopyOnWriteArrayList` suits lists whose traversals vastly outnumber mutations. You still meet it through `Stack`, which extends `Vector` and whose own Javadoc prefers `Deque`, and in older APIs such as Swing's `DefaultTableModel`. ## Replacing one Changing a `Vector` to an `ArrayList` is not purely cosmetic. Check first: - whether the list is really shared between threads, because the locks disappear silently; - whether code synchronizes on the `Vector` itself, or subclasses it and uses the `protected` fields `elementData`, `elementCount` or `capacityIncrement`; - whether code calls `elements()` or `capacity()`, which `ArrayList` does not have.

  • Does a positive capacityIncrement change the cost of appending to a Vector?
    Yes. Capacity then grows by a fixed amount, so the number of reallocations rises in proportion to the size, and each one copies every element so far. Total copying turns quadratic, so an append is no longer amortized constant. Doubling keeps total copying linear. Starting from capacity 10, 100,000 appends copy about 500 million references with an increment of 10, against about 164,000 with doubling.
  • If a Vector's iterator takes the lock in next() and remove(), why must you still synchronize around a whole traversal?
    Each of those calls holds the monitor only for its own duration, and `hasNext()` takes it not at all. Between calls another thread can change the `Vector`, and the following `next()` then throws `ConcurrentModificationException` on a best-effort basis. Holding `synchronized (v)` around the entire loop stops other threads' locked calls from getting in.
  • How does Vector.elements() differ from Vector.iterator() when the Vector changes during a traversal?
    `iterator()` is fail-fast: a structural change made other than through the iterator makes it throw `ConcurrentModificationException`, best effort. `elements()` returns an `Enumeration` that is not fail-fast, and the Javadoc calls its results undefined, so removing an element during the loop can silently skip another one.

A bank teller serves one request at a time. "What is my balance?" and "withdraw 100" are each handled cleanly, but someone else can be served between them, so the balance you heard may be out of date when you withdraw. Keeping the window for both requests is the synchronized block.

  • Vector is deprecated, so the compiler warns whenever you use it.
  • Because Vector is synchronized, if (!v.contains(x)) v.add(x) is thread-safe.
  • Vector's iterator cannot throw ConcurrentModificationException because its methods are synchronized.
  • Vector always doubles; capacityIncrement has no effect on how it grows.
  • The ArrayList Javadoc guarantees that capacity grows by exactly 1.5 times.
  • Swapping a shared Vector for ArrayList changes nothing because the two are equivalent.

Vector
Java 1.0
ArrayList
Java 1.2
Vector retrofitted to implement List
Java 1.2

Assumes Java 27; Vector's locking and growth and ArrayList's growth are the same in Java 25.

context