Java ProgramsCollectionsVector Example

Vector Example in Java

beginner·  Collections  ·  List

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.

Input
add(Mercury), add(Venus), add(Earth)
Output
First: Mercury, Total: 3

Java Program

Java
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

First: Mercury, Total: 3

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.

How It Works
  1. 1new Vector<String>() creates a resizable list, added to with add() exactly like an ArrayList would be.
  2. 2planets.get(0) reads the element at index 0, the same indexed-access method ArrayList also provides.
  3. 3planets.size() reports how many elements the vector currently holds.
  4. 4Every method call here would look identical if Vector were swapped for ArrayList — the API surface for basic list operations is the same.
After adding 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.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

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.

Key Concepts

Vectorsynchronized collectionList interface

Related Programs