Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The Vector class in Java helps create a dynamic array of objects and contains components that can be referenced using an index. They are very much similar to ArrayLists. The size of a Vector can change depending on whether elements are added or removed from it. The Vector class implements the List interface, which is used to define an ordered collection of elements.
Now, let us learn about the functions/methods used to manipulate the size and contents of a vector.
The Vector class is synchronized and has some legacy methods that are absent in the collection framework.
A vector tries to optimize storage management by maintaining a capacity and a capacityIncrement variable. The capacity is always at least as large as the vector size, and the vector's storage increases in the size of capacityIncrement.
Declaration:
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
You can also try this code with Online Java Compiler
It constructs a default empty Vector with an initial capacity of ten.
Vector<E> v = new Vector<E>(int size);
It constructs a Vector with a specified initial capacity.
Vector<E> v = new Vector<E>(int size, int incr);
It constructs a Vector with a specified initial capacity and increment. It specifies the number of elements to be allocated each time a vector is resized.
Vector<E> v = new Vector<E>(Collection c);
It creates a Vector with elements that are part of a Collection c.
Methods
Methods
Description
add(int index, E element)
It inserts the given element at the specified position in the vector. If the index is not specified, it appends the given element to the end of the vector.
addAll(int index, Collection c)
It inserts all the elements of a specified collection into the vector, starting at the given position. If the index is not specified, it appends the elements of the given collection to the end of the vector.
addElement(E obj)
It appends the given component to the end of the vector.
clear()
It clears all the elements of the vector.
clone()
It returns a shallow copy of the vector instance.
copyInto(Object[] arr)
It copies the contents of the vector into the specified array.
contains(Object o)
It returns true if the vector contains the specified element.
elementAt(int index)
It returns the component at the given index.
firstElement()
It returns the first element of the vector.
lastElement()
It returns the last element of the vector.
forEach(Consumer action)
It performs the given action for each element of the iterable until all elements have been processed or the action throws an exception.
get(int index)
It returns the element at the specified position in the list.
indexOf(Object o)
It returns the index of a given element in the list.
isEmpty()
It returns true if the vector is empty.
iterator()
It returns an iterator over the elements of the list in a proper sequence.
lastIndexOf(Object o)
It returns the index of the last occurrence of a given element in the list, or -1 if it is not present.
listIterator()
It returns a list iterator over the elements of the list in a proper sequence.
remove(int index)
It removes the element present at the given index.
removeAll(Collection c)
It removes all the elements which are also present in the given collection.
removeIf(Predicate filter)
It removes the elements which satisfy the given predicate.
removeRange(int from, int to)
It removes all the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
replaceAll(UnaryOperator operator)
It replaces each element of the list with the result of applying the operator to that element.
retainAll(Collection c)
It retains the elements of the vector that are contained in the Collection.
set(int index, E element)
It replaces the element at the specified position with the given element.
size()
It returns the number of elements in the list.
setSize(int newsize)
It updates the size of the vector.
sort(Comparator c)
It sorts the list according to the order mentioned by the specified comparator.
spliterator()
A spliterator is an object used for traversing and partitioning elements of a source. This method creates a fail-fast spliterator over the elements of the vector.
subList(int from, int to)
It returns a portion of the list between the specified fromIndex, inclusive, and toIndex, exclusive.
toString()
It returns a string representation of the vector and its contents as well.
toArray()
It returns an array of all the elements in the vector in proper sequence.
trimToSize()
It trims the capacity of the vector instance to be the list's current size.
First Element: A
Element at index 2: C
Vector: A, B, C, D, E,
Remove elements
import java.util.*;
public class Main {
public static void main(String[] args) {
Vector<String> alpha= new Vector<>();
// Using the add() method
alpha.add("A");
alpha.add("B");
alpha.add("C");
alpha.add("AD");
alpha.add("E");
System.out.println("Vector: " + alpha);
System.out.println("Removing element at index 2: " + alpha.remove(2));
System.out.println("Removing elements starting with A .. ");
alpha.removeIf(e -> e.startsWith("A"));
System.out.println("Vector: " + alpha);
}
}
You can also try this code with Online Java Compiler
Thread Safety: Vectors are synchronized, making them safe for use in multi-threaded environments without requiring external synchronization.
Dynamic Sizing: Vectors automatically resize themselves to accommodate more elements when the capacity is exceeded.
Legacy Support: Vector has been part of Java since its early versions, providing backward compatibility with older code.
Built-in Methods: Vectors offer a rich set of methods for adding, removing, and manipulating elements, making them easy to use in various scenarios.
Fail-Safe Iteration: Iterators for Vectors are fail-safe, meaning they operate over a cloned copy of the collection, avoiding concurrent modification exceptions.
Disadvantages of using Vector in Java
Performance Overhead: Due to synchronization, Vectors have higher performance overhead compared to unsynchronized collections like ArrayList.
Outdated: Vector is considered outdated and has been largely replaced by collections from the java.util.concurrent package and ArrayList for most use cases.
Memory Wastage: Vectors tend to over-allocate memory when resizing, leading to wasted memory if not properly managed.
Inefficient in Single-Threaded Applications: Since Vectors are synchronized, they can be slower and less efficient in single-threaded applications compared to alternatives like ArrayList.
Frequently Asked Questions
What are common errors one can encounter during the declaration of a vector?
If the size parameter of the vector constructor is passed a negative value, it throws an IllegalArgumentException. A NullPointerException is thrown when a null value is passed instead of a collection in the constructor.
Is a Vector a class or interface in Java?
Vector is a class in Java, part of the java.util package. It implements the List interface and provides a dynamic array that can grow as needed. Vector is synchronized, making it thread-safe but slower than non-synchronized alternatives.
What is the difference between Vector and ArrayList?
The main difference is that Vector is synchronized, making it thread-safe, while ArrayList is not. Due to this, Vector has more overhead and performs slower in single-threaded environments, whereas ArrayList offers better performance for non-threaded applications.
Conclusion
In this article, we explored the Vector class in Java, starting with its significance as a dynamic array in data structures. We looked its constructors, methods, and key operations. We also discussed the advantages and disadvantages of using Vectors, offering a comprehensive understanding of its application in Java.