Sobes.tech
Junior

What is a Vector in Java?

sobes.tech AI

Answer from AI

Vector is a legacy class in Java that implements a dynamic array. It is thread-safe because most of its methods are synchronized using the synchronized keyword. This makes it less performant compared to ArrayList in a single-threaded environment.

Main characteristics:

  • Synchronization: All methods that modify the state of Vector (e.g., add(), remove()) are synchronized.
  • Performance: Due to synchronization, it has lower performance compared to unsynchronized collections like ArrayList.
  • Legacy functionality: Partially inherits methods from the older AbstractList class.
  • Capacity increase: Automatically increases its size when needed. You can specify an increment for capacity increase at creation.

Example of simple usage:

// Creating a Vector
Vector<String> vector = new Vector<>();

// Adding elements
vector.add("Element 1");
vector.add("Element 2");

// Getting an element
String element = vector.get(0);

// Vector size
int size = vector.size();

// Iteration
for (String item : vector) {
    // ...
}

// Removing an element
vector.remove("Element 1");

Comparison with ArrayList:

Attribute Vector ArrayList
Synchronization Synchronized Unsynchronized
Performance Slower (in single-threaded) Faster
Legacy Yes No
Capacity increase Can set an increment Increases by 50%

In modern Java applications, Vector is rarely used. In most cases, it is preferable to use ArrayList for unsynchronized lists or CopyOnWriteArrayList or wrap ArrayList with Collections.synchronizedList() for thread-safe scenarios.

What is a Vector in Java? — Java - sobes.tech