Java Vector Class: Usage Guide
One common use of the Vector class in Java is as a dynamic array that automatically expands and contracts, allowing for the storage of objects of different data types.
- Declare and instantiate a Vector object:
- Create a Vector object to store integers.
- Add elements:
- vector.add(10); // Add element to the end of the Vector
vector.add(20);
vector.add(30);
vector.add(1, 15); // Insert element at a specified position - Accessing elements:
- Retrieve the element at a specified position in the vector.
- Modify elements:
- update the element at the specified position to 25 in the vector
- Remove elements:
- vector.remove(0); // Remove element at specified position
vector.removeElement(30); // Remove specified element - Iterate through the Vector.
- Alternatively, you can use an enhanced for loop to iterate through the vector and print each element.
- Check if the Vector is empty.
- A boolean variable named isEmpty is assigned the value of vector.isEmpty().
- Get the size of the Vector:
- size variable is assigned the size of the vector.
- Clear the Vector:
- Clear the vector.
It is important to note that the Vector class is thread-safe, which means it is suitable for multi-threaded environments. However, in a single-threaded environment, it is recommended to use ArrayList instead of Vector because ArrayList has better performance.