In this tutorial will learn about Vector Class in Java with some cool and easy examples.
Vector Class in Java
In Java, the Vector class is a part of the java.util package and is used to create dynamic arrays that can grow or shrink in size as needed. It’s similar to the ArrayList class, but Vector is synchronized, meaning it’s thread-safe, making it suitable for situations where multiple threads might access the same collection concurrently.
import java.util.Vector; public class VectorExample { public static void main(String[] args) { // Creating a Vector Vector<Integer> vector = new Vector<>(); // Adding elements to the Vector vector.add(10); vector.add(20); vector.add(30); // Accessing elements System.out.println("Element at index 0: " + vector.get(0)); System.out.println("Element at index 1: " + vector.get(1)); System.out.println("Element at index 2: " + vector.get(2)); // Iterating through the Vector System.out.println("Iterating through the Vector:"); for (Integer element : vector) { System.out.println(element); } } }
Dynamic Sizing: Like ArrayList, Vector automatically resizes itself when its capacity is exceeded.
Synchronization: Unlike ArrayList, all methods of Vector are synchronized, which means they are thread-safe. This makes Vector suitable for multi-threaded environments. However, this synchronization overhead can impact performance, so ArrayList is generally preferred for single-threaded applications.
Legacy Class: Vector is one of the older classes in Java, introduced in JDK 1.0, and it’s part of the original collection framework. Its use has become less common with the introduction of the more modern ArrayList and other collection classes.
Enumeration: Vector provides an enumeration interface (Enumeration<E> elements()) for iterating through its elements. While enumerations are less flexible than iterators, they were used before iterators were introduced in Java 2.
Backward Compatibility: Vector is part of the legacy collection framework and is retained for backward compatibility reasons. However, its use is discouraged in favor of ArrayList or other more modern collection classes.
output:
Element at index 0: 10 Element at index 1: 20 Element at index 2: 30 Iterating through the Vector: 10 20 30