Let’s look at the scenario of how vector in Java works. Say we have to build a tree data structure and store the value of the nodes.
Since we do not know the number of nodes in advance, we need an appropriate data structure that works for us. We could use Array, but we initialize it with a fixed size that cannot be changed in the future.
The problem arises when the Array becomes full, and we want to insert more nodes in the tree. Since Arrays cannot be expanded we need to look for another data structure whose size can be changed dynamically and Vectors come to our rescue.
What is Vector in Java?
Vector is a data structure that is used to store a collection of elements. Elements can be of all primitive types like int, float, Object, etc. Vectors are dynamic in nature and accordingly, grow or shrink as per the requirement.
Vector Class in Java is found in the java.util package.
Vector class is a child class of the AbstractList class and implements the List interface. Therefore we can use all the methods of the List interface.
Vectors are known to give ConcurrentModificationException when accessed concurrently at the time of modification.
When a Vector is created, it has a certain capacity to store elements that can be defined initially. This capacity is dynamic in nature and can be increased or decreased.
By definition, Vectors are synchronized, which implies that at a time, only one thread is able to access the code while other threads have to wait. Due to this, Vectors are slower in performance as they acquire a lock on a thread.
Declaration of Vector in Java
Syntax
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Here, E denotes the Element Type
Vector Class extends AbstractList and implements multiple interfaces like Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess interfaces.
The directly known subclass is Stack.
Important points regarding the Increment of vector capacity
In each allocation cycle, Vector will expand in accordance with the increment if one is supplied. However, if the increment is left unspecified, each allocation cycle doubles the vector's capacity. Three protected data members are defined by Vector:
int capacityIncreament: Contains the value of the increment.
int elementCount: Number of elements that are currently stored in the vector.
Object elementData[]: The vector is kept in an array that is stored in it
Common Errors in the Declaration of Vectors
The following are typical mistakes made in the declaration of vectors:
If the InitialSize of the vector defined is negative, Vector throws an IllegalArgumentException.
It throws a NullPointerException if the specified collection is null.
Constructors in Vectors
Vector(): A default vector of capacity 10 gets created while calling this constructor.
Vector<E> defaultVector = new Vector<E>(); //Here E represents Element Type.
Vector(int size): A vector is created with the given size as its capacity.
Vector<E> initialCapacityVector = new Vector<E>(int size);
Vector(int size, int increment): A vector is created with the given size as its initial capacity, and whenever the capacity needs to be increased, it is increased by the given increment count.
Vector<E> incrementalVector = new Vector<E>(int size, int increment);
Vector(Collection c): A Java vector is constructed from the given collection with the same order of elements as in the collection.
Vector<E> vector = new Vector<E>(Collection c);
There are also three protected data members (Protected fields are the data members that can be accessed either within the class or from the derived class) in the Vector class.
int capacityIncreament: Contains the increment value.
int elementCount: Number of elements currently in vector stored in it.
Object elementData[]: Array that holds the vector is stored in it.
While initializing vectors in Java, one should keep in mind some exceptions that can occur:
IllegalArgumentException: This is thrown if the initial size of the vector defined is negative.
NullPointerException: This is thrown if the specified collection passed in the constructor is null.
Example: Initializing Java Vector Constructors
package p4n.in;
import java.util.Vector;
public class P4n{
public static void main(String[] args) {
// creating default vector(with capacity equals to 10)
Vector<Integer> defaultVector = new Vector<Integer>();
// creating a vector with the Capacity equals to 100
Vector<Integer> fixedSizeVector = new Vector<Integer>(100);
fixedSizeVector.add(100);
fixedSizeVector.add(100);
fixedSizeVector.add(100);
// creating a vector of given Capacity = 30 and Increment=20
// Here vector capacity will increase by 20 when needed
Vector<Integer> incrementalVector = new Vector<Integer>(30, 20);
// creating a vector with the given collection
Vector<Integer> copyConstructorVector = new Vector<Integer>(
fixedSizeVector
);
System.out.println(
"Vector defaultVector has capacity : " +
defaultVector.capacity() +
" elements"
);
System.out.println(
"Vector fixedSizeVector of capacity : " +
fixedSizeVector.capacity() +
" elements"
);
System.out.println(
"Vector incrementalVector of capacity : " +
incrementalVector.capacity() +
" elements"
);
System.out.println(
"Vector copyConstructorVector of capacity : " +
copyConstructorVector.capacity() +
" elements"
);
}
}
Output:
Vector defaultVector has capacity : 10 elements
Vector fixedSizeVector of capacity : 100 elements
Vector incrementalVector of capacity : 30 elements Vector copyConstructorVector of capacity : 3 elements
Explanation:
In the above code, we are performing the following steps:
Firstly, we made a defaultVector with an initial capacity of 10.
Then we created another vector, fixedSizeVector with Capacity = 100, and added 3 elements into it.
Then we created a third vector, incrementalVector with Capacity 30 and its capacity will increase by 20 whenever we want to add elements more than its capacity.
Then we create a vector, copyConstructorVector which is initialized from the elements of the fixedSizeVector.
Notice that the size of fixedSizeVector and capacity of copyConstructorVector is the same.
Then, we compare the capacity of all the vectors using the capacity() method.
Increment of Vector Capacity
By default, the vector increases its capacity by double. However, if an increment is specified in its constructor, Vector will grow in accordance with it in each allocation cycle.
Let’s take a look at the following example:
In the below code, we can see how the capacity() function is behaving:
package p4n.in;
import java.util.Vector;
public class Main {
public static void main(String args[]) {
// A new vector with size = 4, increment = 2.
Vector myVector = new Vector(4, 2);
System.out.println("Initial size: " + myVector.size());
System.out.println("Initial capacity: " + myVector.capacity()); // Initial capacity: 4
myVector.addElement(new String("Java"));
myVector.addElement(new String("C++"));
myVector.addElement(new String("Python"));
myVector.addElement(new String("Javascript"));
System.out.println("Capacity after four additions: " + myVector.capacity()); // Capacity after four additions: 4
// Since, the size, and capacity are now equal,
// Addition of one more element will increase the capacity by 2.
myVector.addElement(100);
System.out.println(
"Capacity after one more addition: " + myVector.capacity()
); // Capacity after one more addition : 6
myVector.addElement(2.0);
myVector.addElement(72);
System.out.println("Capacity after two more additions: " + myVector.capacity()); // Capacity after two addition: 8
System.out.println("Final Vector = " + myVector);
}
}
Output:
Initial size: 0 Initial capacity: 4 Capacity after four additions: 4 Capacity after one more addition: 6 Capacity after two more additions: 8 Final Vector = [Java, C++, Python, Javascript, 100, 2.0, 72]
Explanation:
In the above code, we are performing the following steps:
We are making a vector called myVector with an initial capacity of 4 and a capacity increment value as 2. If the vector gets full and we try to add another element, the vector capacity will be increased by 2 every time.
Then we are adding four elements in myVector. Now, we attempt to add one more element but since the vector gets full, its capacity increases by 2 and the new capacity is 6.
Then we add two more elements making its capacity = 8 and size = 7.
Example
Java Program to Demonstrate Working of Vector :
// Importing required classes
package p4n.in;
import java.io.*;
import java.util.*;
// Main class
class P4n{
// Main driver method
public static void main(String[] args)
{
// Size of the Vector
int n = 5;
// Declaring the Vector with
// initial size n
Vector<Integer> v = new Vector<Integer>(n);
// Appending new elements at
// the end of the vector
for (int i = 1; i <= n; i++)
v.add(i);
// Printing elements
System.out.println(v);
// Remove element at index 3
v.remove(3);
// Displaying the vector
// after deletion
System.out.println(v);
// iterating over vector elements
// using for loop
for (int i = 0; i < v.size(); i++)
// Printing elements one by one
System.out.print(v.get(i) + " ");
}
}
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Operations in Java Vectors
The most common operations include:
Adding elements to the vector.
Iterating over the elements we added in the vector.
Replacing elements at certain indexes in the vector.
Removing elements from the vector.
Adding elements
To add elements in any given vector, we can use add() method. This method can be implemented in different ways by overloading the method.
In the below code, we are performing the following steps:
We have initialized a new vector, ourVector with a capacity 100
Then we are two adding elements to it.
package p4n.in;
import java.util.Vector;
public class Main {
public static void main(String[] arg) {
Vector<Integer> ourVector = new Vector<Integer>(100);
// Let’s add two elements
// Inserting elements at the end of the vector.
ourVector.add(2);
// Inserting element at index = 1, i.e. end of the vector
// We cannot insert element at any index > size of the vector
ourVector.add(1, 3);
System.out.println("Vector is: " + ourVector);
}
}
Output:
Vector is: [2,3]
Iterating over the elements
Although there are many ways to iterate through the Vector, the most basic and widely used way is by using a basic for loop in combination with a get() method to get the element at the given index.
In the below code, we are performing the following steps:
Here, we created a vector and added 2 elements, “a” and “b” .
Then iterate over the vector with for loop and use the get() method to fetch those values.
We can even use the for each loop to get the same output.
package p4n.in;
import java.util.Vector;
public class p4n{
public static void main(String args[]) {
Vector<String> ourVector = new Vector<>();
ourVector.add("a");
ourVector.add("b");
// basic for loop
for (int index = 0; index < ourVector.size(); index++) {
System.out.print(ourVector.get(index) + " ");
}
// Using the for each loop
for (String str : ourVector) {
System.out.print(str + " ");
}
}
}
Output:
Using get() method: a b
Using for each loop:
a b
Replacing elements
Now let’s say we added a few elements, and we realize some of them need to be changed. This can be done using the set() method, and this takes an index as an argument and the new element which needs to be inserted at that index.
In the below code, we are performing the following steps:
Here, we created a java vector and added 2 elements “happy” and “crying”.
Then, using the set() method we replace the element at index 1 i.e “crying” with “laughing”.
package p4n.in;
import java.util.Vector;
public class p4n{
public static void main(String args[]) {
Vector<String> ourVector = new Vector<>();
ourVector.add("happy");
ourVector.add("crying");
System.out.println("Vector before update: " + ourVector);
// Using set() method to replace “crying” with “laughing”
ourVector.set(1, "laughing");
System.out.println("Vector after update: " + ourVector);
}
}
Output:
Vector before update: [happy, crying]
Vector after update: [happy, laughing]
Removing Elements
To remove any element from the vector in java, we can use the remove() method. This method can be implemented in 2 ways:
remove(Object): This simply removes the object from the Vector. If there are multiple instances of the object, then only the first occurrence of the object is removed.
remove(int index): This removes the element present at that specific index in the Vector. Do note that after removing the element from the vector, the vector fills the space by shifting all the elements to the left, and hence the indices of the elements are updated.
package p4n.in;
import java.util.Vector;
public class p4n{
public static void main(String[] arg) {
Vector ourVector = new Vector();
ourVector.add("p4n");
ourVector.add(2);
ourVector.add(3);
ourVector.add("InterviewBit");
ourVector.add(10);
System.out.println(" Original Vector : " + ourVector);
// removing the first occurrence of b
ourVector.remove("b");
System.out.println("Vector after removing b: " + ourVector);
// removing the element at index 0
ourVector.remove(0);
System.out.println(
"Vector after removing element at index 0: " + ourVector
);
// removing the Integer element with value = 10
ourVector.remove(new Integer(10));
System.out.println(
"Vector after removing Integer valued 10: " + ourVector
);
}
}
Output:
Original Vector : [p4n, 2, 3, InterviewBit, 10]
Vector after removing b: [p4n, 2, 3, InterviewBit, 10] Vector after removing element at index 0: [2, 3, InterviewBit, 10] Vector after removing Integer valued 10: [2, 3, InterviewBit]
IMPORTANT:
Notice the way we have removed the Integer with value = 10 in the code snippet above. We cannot simply pass 10 as the argument of the remove function since it will interpret it as an index, not an element.
Comments