The Vector class provides the capability to implement a growable array of objects.
In Core Java, the Vector
class is a part of the Java Collections Framework and is present in the java.util
package. It is a legacy class that was part of the original version of Java and was later retrofitted to implement the List interface. Here are some key points about the Vector
class:
- Dynamic Array: Similar to an array, it is a dynamic array that can grow or shrink in size.
- Synchronized: Unlike some other collection classes like
ArrayList
,Vector
is synchronized. This means that all of its methods are thread-safe, making it suitable for situations where multiple threads may access and modify the Vector concurrently. - Legacy Class: While
Vector
provides synchronization, it has been largely replaced by the more modern and efficientArrayList
in most scenarios. The synchronization inVector
can introduce performance overhead, and for single-threaded applications,ArrayList
is often preferred. - Enumeration: It includes methods like
elements()
that return an Enumeration of the elements of the vector, which is a legacy interface for iterating over collections.
Here is a simple example of using a Vector:
import java.util.Vector;
import java.util.Enumeration;
public class VectorExample {
public static void main(String[] args) {
// Creating a Vector
Vector<String> vector = new Vector<>();
// Adding elements
vector.add("Java");
vector.add("is");
vector.add("cool");
// Accessing elements
for (String element : vector) {
System.out.print(element + " ");
}
System.out.println();
// Using Enumeration to iterate
Enumeration<String> enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
System.out.print(enumeration.nextElement() + " ");
}
}
}
In modern Java development, it’s more common to use ArrayList
or other collection classes due to their better performance in most scenarios.