Java Vector
In this tutorial, we will learn about what is java.util.Vector, methods of it, its use cases, major differences from ArrayList and working example of a Vector.
Vector class
java.util.Vector
is a legacy class that is like ArrayList but major important difference it is a thread-safe implementation but ArrayList is not a thread safe implementation.
Vector was introduced in the early days of Java when multi-threading was not as well-understood as compared to today, and the designers of the language wanted to provide a collection class that could be used safely in a multi-threaded environment
Vector implementation of the List interface, which means that it has all the same methods as ArrayList, plus a few additional methods that are specific to Vector.
Vector use-cases:
Some of the common use cases of Vector are:
- In multi-threaded applications where thread-safety is a concern, Vector can be used to ensure that data is accessed and modified in a thread-safe manner.
- In situations where the size of the list is not known in advance, but the list needs to be resizable, Vector can be used. Unlike arrays, Vectors can grow or shrink as needed, making them more flexible.
- When the list needs to be sorted, Vector provides a sort() method that can be used to sort the elements in the list.
Vector example:
import java.util.Vector;
import java.util. Collections;
public class VectorExample {
public static void main(String[] args) {
// Creating a vector
Vector<String> vec = new Vector<String>();
// Adding elements to the Vector
vec.add("Tomato");
vec.add("Cabbage");
vec.add("Carrot");
vec.add("Onion");
vec.add("Beetroot");
vec.add(1,"Broccoli");
vec.remove("Cabbage");
// Printing the vector
System.out.println("Vector: " + vec);
// Removing an element from the vector
vec.remove("Broccoli");
// Printing the vector after removal
System.out.println("Vector after removal: " + vec);
}
}
Output:
Vector: [Tomato, Broccoli, Carrot, Onion, Beetroot]
Vector after removal: [Tomato, Carrot, Onion, Beetroot]
Explanation:
Based on the above example, Vector is easy to use and provides all the functionality of ArrayList and addition to this it is a thread-safe implementation.
It is important to note that Vector can be less efficient than ArrayList because of its thread-safety features, Vector is useful where multiple threads will not be using Vector.
Considering current fast-growing world, every requirement demands in terms of performance.
Note: The java.util.Vector
class is an old implementation of the List
interface and it is a thread-safe but all the features of it replaced by the ArrayList
and LinkedList
classes except thread-safety.
Conclusion:
In this tutorial, we have covered what is Vector, methods of it, along with working example and discussed on its differences compared to other implementation class of List.