Skip to content
C

Vector

Vector is an older implementation of the List interface, very similar to ArrayList, but with all its methods synchronized, meaning it is safe to use across multiple threads simultaneously.


1. What is Vector?

Vector is an older implementation of the List interface, very similar to ArrayList, but with all its methods synchronized, meaning it is safe to use across multiple threads simultaneously.

2. Why is it used?

Vector is used in situations where thread safety for list operations is genuinely required, though in modern Java, other approaches are often preferred for new projects.

3. Real-Life Example

Think of a single shared notice board where only one person is allowed to write on it at a time, ensuring nothing gets overwritten or lost due to two people writing simultaneously. Vector behaves similarly across threads.

4. Syntax

java
Vector<DataType> vectorName = new Vector<>();

5. Example Program

java
import java.util.Vector; public class VectorDemo { public static void main(String[] args) { Vector<String> colors = new Vector<>(); colors.add("Red"); colors.add("Blue"); System.out.println(colors); } }

Output:

[Red, Blue]

6. Key Points to Remember

  • Vector is synchronized (thread-safe), unlike ArrayList.
  • Because of this synchronization, Vector is generally slower than ArrayList in single-threaded programs.
  • Vector is considered a legacy class; ArrayList combined with explicit synchronization (when needed) is usually preferred today.