Java Vector

Introduction

Java Vector is one of the oldest classes in the Java Collection Framework used to store a dynamic collection of objects. It is similar to ArrayList, but with one major difference: Vector is synchronized, making it thread-safe for use in multithreaded environments.

The Vector class belongs to the java.util package and implements the List interface. Vector is generally slower than ArrayList in single-threaded applications.

What is Java Vector?

Vector is a dynamic array implementation in Java that automatically grows as elements are added. It implements the List interface and supports all standard list operations.

Unlike arrays, a Vector does not have a fixed size. When its capacity is exceeded, it automatically allocates more memory.

Key Characteristics

  • Implements the List interface
  • Dynamic size
  • Thread-safe (synchronized)
  • Maintains insertion order
  • Allows duplicate elements
  • Allows multiple null values
  • Supports index-based access
  • Automatically increases capacity

Java Vector Hierarchy


Object
   │
AbstractCollection
   │
AbstractList
   │
Vector
   │
 Stack

Since Stack extends Vector, it inherits all the methods provided by the Vector class.

Features of Java Vector

Some important features of Vector include:

  • Dynamic resizing
  • Thread-safe operations
  • Maintains insertion order
  • Allows duplicate elements
  • Allows null values
  • Supports random access
  • Rich collection methods
  • Supports Generics
  • Automatic capacity expansion

Syntax

Import Statement


import java.util.Vector;
or
import java.util.*;

Creating a Vector


Vector<String> fruits = new Vector<>();

Using the List interface:


Vector<String> fruits = new Vector<>();

4. Constructor Using Another Collection


Vector<String> list = new Vector<>();
list.add("Java");
list.add("Python");
Vector<String> vector = new Vector<>();

Creates a Vector containing all elements from another collection.

Common Methods of Vector

Method Description
add() Adds an element
addFirst() Adds an element at the beginning
addLast() Adds an element at the end
get() Returns an element by index
getFirst() Returns the first element
getLast() Returns the last element
remove() Removes an element
removeFirst() Removes the first element
removeLast() Removes the last element
set() Updates an element
size() Returns the number of elements
contains() Checks whether an element exists
clear() Removes all elements
peek() Returns the first element without removing it
poll() Returns and removes the first element

Example 1: Creating a Vector


import java.util.*;

public class VectorExample {

    public static void main(String[] args) {

        Vector<String> fruits = new Vector<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        System.out.println(fruits);
    }
}

Output

[Apple, Banana, Mango]

Example 2: Accessing Elements


import java.util.*;

public class GetExample {

    public static void main(String[] args) {

       Vector<String> colour = new Vector<>();

        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        System.out.println(colors.get(1));
    }
}

Output

Green

Example 3: Updating an Element


import java.util.*;

public class UpdateExample {

    public static void main(String[] args) {

         Vector<String> student = new Vector<>();

        students.add("Rahul");
        students.add("Amit");

        students.set(1, "Vikas");

        System.out.println(students);
    }
}


[Rahul, Vikas]

Example 4: Removing an Element


import java.util.*;

public class RemoveExample {

    public static void main(String[] args) {

        Vector<String> city = new Vector<>();

        cities.add("Delhi");
        cities.add("Mumbai");
        cities.add("Jaipur");

        cities.remove("Mumbai");

        System.out.println(cities);
    }
}

Output

[Delhi, Jaipur]

Example 5: Checking Capacity


import java.util.*;

public class CapacityExample {

    public static void main(String[] args) {

        Vector numbers = new Vector();

        System.out.println("Size: " + numbers.size());
        System.out.println("Capacity: " + numbers.capacity());
    }
}

Output

Size: 0
Capacity: 10

Iterating Through a Vector


import java.util.*;

public class LoopExample {

    public static void main(String[] args) {

        Vector courses = new Vector();

        courses.add("Java");
        courses.add("Python");
        courses.add("Spring Boot");

        for(String course : courses){
            System.out.println(course);
        }
    }
}

Output

Java
Python
Spring Boot

Vector vs ArrayList

Feature Vector ArrayList
Thread Safe Slower Faster
Synchronization Yes No
Dynamic Size Yes Yes
Allows Duplicates Yes Yes
Maintains Order Yes Yes
Recommended for New Projects Rarely Yes

Time Complexity

Operation Time Complexity
Add (End) O(1) (Amortized)
Get O(1)
Set O(1)
Remove (Middle) O(n)
Search O(n)
Insert (Middle) O(n)

Real-life Example

Imagine you’re developing a banking application where multiple threads update a shared list of customer transactions.

Since multiple users may perform deposits, withdrawals, and balance inquiries simultaneously, thread safety becomes important.

Using a Vector ensures that its methods are synchronized, reducing the risk of data inconsistency when accessed by multiple threads.

Other real-world applications include:

  • Legacy enterprise systems
  • Shared configuration lists
  • Inventory management
  • Banking systems
  • Reservation systems
  • Multithreaded desktop applications

Advantages of Vector

  • Dynamic resizing
  • Thread-safe
  • Maintains insertion order
  • Allows duplicate elements
  • Allows null values
  • Rich built-in methods
  • Easy to use
  • Supports Generics
  • Provides backward compatibility with older Java code

Limitations of Vector

  • Slower than ArrayList because of synchronization
  • Higher overhead in single-threaded applications
  • Increased memory usage due to synchronization mechanisms
  • Rarely recommended for modern applications
  • Better thread-safe alternatives are available for many use cases

Common Mistakes

1. Using Vector in Single-Threaded Applications

If synchronization is not required, prefer ArrayList for better performance.

2. Forgetting Generics

Incorrect:


Vector list = new Vector();

Correct:


Vector<String> list = new Vector<>();

3. Accessing an Invalid Index


vector.get(10);

This throws an IndexOutOfBoundsException if the index does not exist.

4. Assuming Vector Is Faster Than ArrayList

Because every public method is synchronized, Vector generally performs slower than ArrayList in single-threaded applications.

5. Ignoring Capacity Planning

When storing a large number of elements, specifying an appropriate initial capacity can reduce the number of internal resizing operations.

Best Practices

  • Prefer the List interface for variable declarations.

Vector<String> list = new Vector<>();
  • Use Generics for compile-time type safety.
  • Choose Vector only when thread safety through built-in synchronization is required.
  • For most single-threaded applications, prefer ArrayList.
  • Specify the initial capacity if the expected number of elements is known.
  • Use enhanced for loops or iterators for traversing elements.

Conclusion

The Java Vector class is a synchronized implementation of the List interface that provides a dynamic, ordered collection of objects. It supports automatic resizing, duplicate elements, null values, and index-based access while ensuring thread safety through synchronized methods.

Although Vector has largely been replaced by ArrayList and newer concurrent collections in modern Java development, it remains an important part of the Java Collection Framework and is still widely encountered in legacy systems and technical interviews.

Related Java Tutorials