Java Vector
In Java, the Vector
class is an implementation of the List
interface that is similar to the ArrayList
class. It uses a dynamic array to store elements, and can automatically grow and shrink as elements are added or removed. However, the Vector
class is different from the ArrayList
class in that it is synchronized, which means that it is thread-safe.
The Vector
class is part of the Java Collections Framework and provides many methods for working with lists of objects. Here are some of the key methods defined in the Vector
class:
boolean add(E element)
: Adds the specified element to the end of the list.void add(int index, E element)
: Inserts the specified element at the specified position in the list.boolean addAll(Collection<? extends E> collection)
: Adds all elements from the specified collection to the end of the list.boolean addAll(int index, Collection<? extends E> collection)
: Inserts all elements from the specified collection into the list, starting at the specified position.E get(int index)
: Returns the element at the specified position in the list.int indexOf(Object element)
: Returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.int lastIndexOf(Object element)
: Returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found.E remove(int index)
: Removes the element at the specified position in the list.boolean remove(Object element)
: Removes the first occurrence of the specified element from the list.E set(int index, E element)
: Replaces the element at the specified position in the list with the specified element.int size()
: Returns the number of elements in the list.void clear()
: Removes all elements from the list.Object[] toArray()
: Returns an array containing all elements in the list.<T> T[] toArray(T[] array)
: Returns an array containing all elements in the list, using the specified array if it is large enough, or creating a new array of the same type if necessary.
The Vector
class is a good choice for situations where you need to use a thread-safe list. However, if thread safety is not a concern, the ArrayList
class is generally faster and more efficient.