Vector Class in Java

In Java, the Vector class is a legacy implementation of the List interface that is similar to the ArrayList class but with the additional feature of being synchronized. Vector provides a resizable array that can grow dynamically as elements are added to it, and ensures that its methods are synchronized to prevent concurrent access by multiple threads.

Here's an example of how to use Vector in Java

import java.util.Vector;
public class VectorExample {
  public static void main(String[] args) {
    // Create a Vector of integers
    Vector<Integer> numbers = new Vector<>();
    // Add elements to the Vector
    numbers.add(10);
    numbers.add(20);
    numbers.add(30);
    // Access elements in the Vector
    int firstNumber = numbers.get(0); // 10
    int lastNumber = numbers.get(numbers.size() - 1); // 30
    // Modify elements in the Vector
    numbers.set(1, 25); // [10, 25, 30]
    // Remove elements from the Vector
    numbers.remove(2); // [10, 25]
    // Iterate over the Vector using a for-each loop
    for (int number : numbers) {
      System.out.println(number);
    }
    // Clear the Vector
    numbers.clear(); // []
  }
}

In this example, we create a Vector of integers called numbers and add three elements to it using the add() method. We then access elements in the Vector using the get() method, and modify elements in the Vector using the set() method. We also remove an element from the Vector using the remove() method. We then iterate over the Vector using a for-each loop, and finally clear the Vector using the clear() method.

Note that Vector provides several other methods, such as indexOf(), isEmpty(), size(), and toArray(), that can be used to manipulate and access elements in the Vector. Additionally, Vector can be used with any object type, including custom objects, by specifying the object type when creating the Vector.

However, it's worth noting that the use of Vector is generally discouraged in modern Java programming, as its synchronized methods can introduce performance overhead and may not be necessary in many cases. Instead, it's often recommended to use the ArrayList class for its superior performance and to use other synchronization mechanisms, such as locks or the Collections.synchronizedList() method, to handle concurrent access to collections.