Vectors are an essential data structure in Java that provides dynamic, resizable arrays, making them a versatile tool for managing collections of data.
What is a Vector in Java ?
A Vector in Java is a part of the Collection Framework. Vector provides a dynamic array-like structure. Unlike traditional arrays vectors can dynamically grow and shrink in size as elements are added or removed, making vectors suitable for various data management tasks.
Properties of Vector
- Insertion Order is preserved in Vectors
- Duplicates are allowed in vectors
- null insertion is possible in vectors
- Vector implements
RandomAccess
,Cloneable
, andjava.io.Serializable
interface. - Vector objects are thread-safe because all methods of vectors are synchronized.
Vector Consturctor
Vector()
Vector v = new Vector();
The constructor creates an empty Vector objet with default initial capacity 10.
Once the vector capacity full then a new Vector object will be created with new capacity. new capacity is calculate as given below
new capacity = current capacity * 2
Vector(int initialCapacity)
Vector v = new Vector( int initialCapacity);
This constructor creates and empty Vector object with the specified initial capacity.
Vector(int initialCapacity, int incrementCapacity)
Vector v = new Vector(int initialCapacity,
int capacityIncrement );
This constructor creates an empty Vector object with the specified initial capacity and capacity increment.
Vector(Collection c)
Vector v = new Vector( Collection c);
This constructor creates an equivalent Vector object for given collection c. Mostly used for inter conversion between Collection objects.
Vector Example in Java
package vector;
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector vector = new Vector();
System.out.println(vector.capacity()); //initial capacity
for(int i=0;i<10;i++){
vector.add(i);
}
System.out.println(vector.capacity());
vector.add("thecodedata");
System.out.println(vector.capacity()); //updated capacity
System.out.println(vector);
}
}