Vector In Java
Vector in Java
The Vector class in Java is a dynamic array implementation that is part of the Java Collections Framework. It provides a resizable array that can grow or shrink as needed. Vectors are similar to ArrayLists but are synchronized, making them thread-safe for use in multi-threaded environments.
Declaration and Initialization
To use a Vector in Java, you need to import the java.util.Vector
package. Here's an example of declaring and initializing a Vector:
import java.util.Vector; public class Example { public static void main(String[] args) {
// Adding elements to the Vector fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Accessing elements System.out.println("Access Element = "+fruits.get(0)); // Output: Apple // Modifying elements fruits.set(1, "Mango"); // Removing elements fruits.remove(2); // Iterating over elements for (String fruit : fruits) { System.out.println("Iterating Elements = "+fruit); }Vector<String> fruits = new Vector<>();} }
Common Vector Operations
Here are some commonly used operations with Vectors:
add(element)
: Adds an element to the end of the Vector.get(index)
: Retrieves the element at the specified index.set(index, element)
: Replaces the element at the specified index with a new element.remove(index)
: Removes the element at the specified index.size()
: Returns the number of elements in the Vector.isEmpty()
: Checks if the Vector is empty.clear()
: Removes all elements from the Vector.
In addition to these methods, Vectors also provide synchronization mechanisms like addElement()
and removeElement()
to ensure thread-safe operations. However, if thread safety is not a requirement, ArrayLists may offer better performance due to their lack of synchronization.