0% completed
The Vector
class in Java is a dynamic array that implements the List
interface. Like ArrayList
, it provides methods for storing, accessing, and manipulating a sequence of elements. However, unlike ArrayList
, Vector
is synchronized by default, which means it is thread-safe and can be used in multithreaded environments where multiple threads access a single instance concurrently.
Vector
also extends AbstractList
and implements additional interfaces such as List
, RandomAccess
, Cloneable
, and Serializable
. This makes it a fully functional and versatile collection class in the Java Collections Framework.
Vector
implements the List
interface, so it supports all standard list operations, including positional access, insertion, removal, and searching.Vector
automatically adjusts its size as elements are added or removed.Vector
are synchronized, providing built-in thread safety, which is useful in concurrent applications.Vector
is part of the Java Collections Framework, it is considered legacy. Modern applications often prefer ArrayList
when synchronization is not required, or use explicit synchronization if needed.Vector<Type> vector = new Vector<Type>();
Vector<Type>
declares a vector that stores objects of the specified Type
.new Vector<Type>()
initializes an empty vector that will grow dynamically as elements are added.In this example, we create a Vector
of strings, add several elements, and then access and display those elements. This demonstrates the basic usage of the Vector
class while highlighting that it implements the List
interface.
Example Explanation:
Vector<String>
named fruits
is created, which can store string elements.add()
method is used to insert elements into the vector.get(0)
method retrieves the first element, showing how the vector supports index-based access as defined by the List
interface.set(1, "Blueberry")
method replaces the element at index 1, demonstrating the ability to update elements.remove(2)
method removes the element at index 2.The Vector
class is a dynamic array that implements the List
interface and offers thread-safe operations through built-in synchronization. Although considered a legacy class, it provides all standard list operations along with additional features like dynamic resizing and thread safety. In this lesson, we reviewed how to create a Vector
, add elements, access and update elements by index, and remove elements. Understanding Vector
is important for working with legacy code and for scenarios where synchronization is required.
.....
.....
.....