Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the collections framework.
In Core Java, a “vector” typically refers to the Vector
class, which is a part of the Java Collections Framework. The Vector
class implements a dynamic array that can grow or shrink as needed. It is similar to the ArrayList
class but is synchronized, meaning it is thread-safe.
Here are some key points about the Vector
class in Java:
- Synchronization: One of the main characteristics of
Vector
is that it is synchronized. This means that multiple threads can safely manipulate aVector
object without the need for external synchronization. - Dynamic Size:
Vector
is a dynamic array, which means it can grow or shrink in size as needed. This is in contrast to traditional arrays in Java, which have a fixed size. - Legacy Class: While
Vector
is part of the Java Collections Framework, it is considered a legacy class. In modern Java programming,ArrayList
is often preferred overVector
becauseArrayList
is not synchronized by default, which can lead to better performance in single-threaded scenarios.
Here’s a simple example of using a Vector
in Java:
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// Creating a Vector
Vector<String> vector = new Vector<>();
// Adding elements
vector.add(“Java”);
vector.add(“C++”);
vector.add(“Python”);
// Accessing elements
System.out.println(“Elements in the vector: “ + vector);
// Removing an element
vector.remove(“C++”);
// Iterating through the vector
System.out.println(“Elements after removal: “);
for (String language : vector) {
System.out.println(language);
}
}
}
In the example above, we create a Vector
, add elements to it, remove an element, and then iterate through the remaining elements.