The Vector
class in Java is a implementation of the List
interface that implements a growable array of objects. It provides methods for adding and removing elements, as well as methods for checking the size of the vector and whether it is empty.
Here is an example of how to use a Vector
in Java:
import java.util.Vector; public class Main { public static void main(String[] args) { // Create a Vector of strings Vector<String> vector = new Vector<>(); // Add some elements to the vector vector.add("Apple"); vector.add("Banana"); vector.add("Cherry"); // Remove an element from the vector String element = vector.remove(1); System.out.println("Removed element: " + element); // Check the size of the vector int size = vector.size(); System.out.println("Size of vector: " + size); // Check if the vector is empty boolean isEmpty = vector.isEmpty(); System.out.println("Vector is empty: " + isEmpty); } }
In this example, we create a Vector
of strings and add some elements to it. We remove an element from the vector, check the size of the vector, and check if the vector is empty.
Note that the Vector
class is synchronized, which means that multiple threads can access it safely without the need for explicit synchronization. However, this synchronization comes at the cost of performance, so it is generally recommended to use other List
implementations, such as ArrayList
, instead of Vector
.