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
Vectorin new code. The Java documentation marksVectoras legacy. PreferArrayListfor single-threaded code andCopyOnWriteArrayListorCollections.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 withArrayList's.Vectordoubles its capacity by default (2×);ArrayListgrows by ~1.5×. IfcapacityIncrementis set on aVector, it grows by that fixed amount instead. - Using the legacy Enumeration API.
Vector.elements()returns anEnumeration, the predecessor toIterator. Modern code should useIteratoror the for-each loop. - Iterating a
VectorwithEnumerationand expecting thread safety. Even thoughVectorsynchronises its methods, iteration viaEnumerationorIteratorcan still seeConcurrentModificationExceptionif another thread modifies theVectorduring iteration.
Best Practices
- Do not use
Vectorin new code. UseArrayList(single-threaded) orCopyOnWriteArrayList/Collections.synchronizedList(multi-threaded). - If you encounter
Vectorin a legacy codebase, prefer replacing it withArrayListafter verifying thread-safety requirements. - For concurrent access, prefer
java.util.concurrentclasses over the legacy synchronised wrappers, as they offer better scalability with finer-grained locking or lock-free algorithms. - When you must interact with legacy
VectorAPIs, synchronise externally on theVectorinstance for compound operations. - Understand
Vectorfor interviews — it comes up frequently as a contrast toArrayList.
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
Vectoris a legacy, synchronised resizable-arrayListfrom Java 1.0; every method issynchronized.- Per-method synchronisation is insufficient for compound operations — races can still occur.
Vectordoubles its capacity on overflow (2×) vs.ArrayList's ~1.5× growth.- Do not use
Vectorin new code; preferArrayListorCopyOnWriteArrayList. - Understanding
Vectorand 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.