← Back to Chapters

Java Vector

? Java Vector

? Quick Overview

Vector is a legacy class in Java that implements a dynamic array. It is part of the java.util package and is synchronized by default, making it thread-safe.

? Key Concepts

  • Vector stores elements in insertion order
  • It automatically grows when capacity is exceeded
  • All methods are synchronized (thread-safe)
  • It allows duplicate and null values

? Syntax / Theory

A Vector can store objects and uses indexing like arrays. It is similar to ArrayList but slower due to synchronization.

? View Code Example
// Creating and using a Vector in Java
import java.util.Vector;

public class VectorDemo {
public static void main(String[] args) {
Vector names = new Vector<>();
names.add("Java");
names.add("Python");
names.add("C++");
System.out.println(names);
}
}

?️ Live Output / Explanation

Output

The output will display all elements stored in the Vector in the order they were added.

[Java, Python, C++]

? Interactive Vector Demo

Visualizing how capacity doubles when the Vector gets full.

Size: 0 | Capacity: 5
 
 

 

? Tips & Best Practices

  • Prefer ArrayList over Vector in single-threaded programs
  • Use Vector only when thread safety is required
  • Avoid legacy classes unless specifically needed

? Try It Yourself

  • Create a Vector of integers
  • Add at least five numbers
  • Remove one element and print the Vector