Vector Example in Java
Problem
Vector is one of Java's original collection classes — a resizable, synchronized list that predates the modern Collections framework but still implements the same List interface ArrayList does.
Add elements to a Vector and read them back by index.
Java Program
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<String> planets = new Vector<>();
planets.add("Mercury");
planets.add("Venus");
planets.add("Earth");
System.out.println("First: " + planets.get(0) + ", Total: " + planets.size());
}
}Output
Core Logic
Vector behaves like an ArrayList for everyday add/get calls, since both implement the same List interface — the real difference between them is under the hood, not in how they're used.
- 1
new Vector<String>()creates a resizable list, added to withadd()exactly like anArrayListwould be. - 2
planets.get(0)reads the element at index 0, the same indexed-access methodArrayListalso provides. - 3
planets.size()reports how many elements the vector currently holds. - 4Every method call here would look identical if
Vectorwere swapped forArrayList— the API surface for basic list operations is the same.
Mercury, Venus, and Earth, get(0) returns "Mercury" and size() returns 3.Key Point: Vector's methods are internally synchronized, making it thread-safe for concurrent access — but that safety comes with locking overhead on every call, which is why ArrayList (unsynchronized) is preferred for ordinary single-threaded use, with Collections.synchronizedList() or a concurrent collection reached for instead when thread safety is genuinely needed today.
Why: add() and get() cost the same as they would on an ArrayList — amortized constant time each — the synchronization Vector adds affects concurrent throughput, not this asymptotic complexity.