In this article we are going see what is Java Vector, why do we use Vector in java and its commonly used methods with simple examples.

  1. What is Java Vector ?

Vector is a legacy collections class in java.util package. Vector class is used to hold a group of elements and it is one of the  implementation class for List interface.

  1. 1. Java Vector Characteristics:

  1. The underlying data structure is resizable array (or) growable array.
  2. Duplicate objects are allowed.
  3. Insertion order is preserved ( means ordered).
  4. Heterogeneous objects are allowed (non generic version).
  5. Null insertion is possible.
  6. Implements Serializable, Cloneable and RandomAccess interfaces.
  7. Every method present in Vector is synchronized and hence Vector is Thread safe.

  1. 2. Why do we use Vector ?

ArrayList has the similar features but not synchronized. Vector methods are synchronized, so whenever thread safety required to hold collection of elements Vector is good choice over ArrayList. ArrayList is faster, since it is non-synchronized, while vector operations give slower performance since they are synchronized. If we don’t have any explicit requirements for using either of them, we use ArrayList over vector.

2. Creating a Java Vector instance

Vector class provides below constructors to create a Vector instance.

Copy to Clipboard

3. Adding elements to Vector

Copy to Clipboard

4. Get elements from Vector

Copy to Clipboard

5. Update elements in Java Vector

Copy to Clipboard

6. Remove elements from Vector

Copy to Clipboard

7. Iterate Vector elements

There are several ways to iterate Java Vector, in this example demonstrating how we iterate Vector using Enumeration  with elemetnts() of Vector class.

Copy to Clipboard

Output

Copy to Clipboard