Vector

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Vector is a legacy class similar to ArrayList (it uses a resizable array).
  • Unlike ArrayList, almost all methods in Vector are synchronized, making it thread-safe.
  • It is considered obsolete; modern code should use ArrayList (or CopyOnWriteArrayList for thread safety).

Concept

Vector has been around since Java 1.0, before the Collections Framework even existed. It was retrofitted in Java 1.2 to implement the List interface.

Synchronization Overhead

Because almost every method (like add(), get(), size()) in Vector is synchronized, threads must obtain a lock on the object before executing the method. In a single-threaded environment, acquiring and releasing this lock for every single operation creates unnecessary performance overhead.

Resizing

When a Vector runs out of space, it doubles its array size (increases by 100%), whereas ArrayList increases by 50%.

Examples

import java.util.Vector;

public class VectorExample {
    public static void main(String[] args) {
        Vector<String> vector = new Vector<>();
        
        vector.add("One");
        vector.add("Two");
        
        // Legacy method from Java 1.0 (does the same as add)
        vector.addElement("Three"); 
        
        System.out.println(vector.get(1)); // "Two"
        
        // Vector is synchronized, but iterating over it still 
        // requires manual synchronization to be safe from 
        // ConcurrentModificationException
        synchronized(vector) {
            for(String s : vector) {
                System.out.println(s);
            }
        }
    }
}

Interview Questions

Q: Why is Vector considered obsolete?
A: Vector synchronizes at the method level. This is usually the wrong granularity for thread safety. If a thread needs to check if the vector is not empty, and then get the first element, both operations are individually synchronized, but the sequence is not. Another thread could clear the vector in between the two calls.
Instead of Vector, developers should use Collections.synchronizedList(new ArrayList<>()) or concurrent collections like CopyOnWriteArrayList.

Q: What is the difference in resizing behavior between Vector and ArrayList?
A: When their internal arrays become full, ArrayList increases its capacity by 50%, whereas Vector doubles its capacity (increases by 100%). You can also specify an exact “capacity increment” in the Vector constructor, a feature ArrayList lacks.