Java Vector
The Vector
class in Java is a part of the Java Collection Framework (JCF) and implements the List interface. It uses a dynamic array to store the elements and is synchronized, making it thread-safe.
This blog provides a detailed understanding of the Vector class, its characteristics, constructors, commonly used methods, and usage examples.
Characteristics of Vector#
- Thread-safe: All methods are synchronized.
- Dynamic array: Grows as elements are added.
- Allows duplicates: Like any List, Vector allows duplicate elements.
- Maintains insertion order.
Declaration#
Constructors#
Constructor | Description |
---|---|
Vector() | Creates an empty vector with initial capacity of 10. |
Vector(int initialCapacity) | Creates a vector with the specified initial capacity. |
Vector(int initialCapacity, int capacityIncrement) | Creates a vector with specified capacity and increment. |
Vector(Collection<? extends E> c) | Creates a vector containing elements of the specified collection. |
Commonly Used Methods#
Method | Description |
---|---|
add(E e) | Adds an element to the end of the vector. |
add(int index, E element) | Adds an element at a specific index. |
get(int index) | Returns element at specified position. |
set(int index, E element) | Replaces element at specified position. |
remove(int index) | Removes element at specified index. |
size() | Returns the number of elements in the vector. |
isEmpty() | Checks if vector is empty. |
clear() | Removes all elements from the vector. |
Examples#
1. Adding and Printing Elements#
Output:
2. Accessing and Modifying Elements#
Output:
3. Removing Elements#
Output:
4. Checking Size and Clearing Vector#
Output:
When to Use Vector#
Use Vector
when:
- You need thread-safe operations.
- You are working in a multi-threaded environment.
However, in most modern applications, ArrayList
is preferred over Vector
for single-threaded environments due to better performance.
Conclusion#
The Vector
class is a legacy class that is synchronized and maintains insertion order. It's useful when thread safety is required without external synchronization. In the next blog, we will cover Stack, which extends Vector and operates in a LIFO manner.