The add()
method of the Vector
class can be used to add an element at the specific index of a Vector
object. The index of the elements present at and after the passed index will be shifted upwards (increased by 1).
The
Vector
class is a growable array of objects. The elements ofVector
can be accessed using an integer index, and the size of aVector
can be increased or decreased. Read more aboutVector
here.
public void add(int index,E element)
This method takes two arguments, which are as follows:
index
at which the new element is to be added. The index
should be positive and less than or equal to the size of the Vector
object. Otherwise, the ArrayIndexOutOfBoundsException
error will be thrown.
index >= 0 && index <= size()
element
to be added to the Vector
object.This method doesn’t return any value.
import java.util.Vector;class Add {public static void main( String args[] ) {// Creating VectorVector<Integer> vector = new Vector<>();// add elememtsvector.add(1);vector.add(3);vector.add(5);System.out.println("The Vector is: " + vector); // [1,3,5]vector.add(1, 2); // [1,2,3,5]System.out.println("\nAfter calling vector.add(1,2). The Vector is: " + vector);vector.add(3, 4); // [1,2,3,4,5]System.out.println("\nAfter calling vector.add(3,4). The Vector is: " + vector);}}
Please click the “Run” button above to see how the add()
method works.
In line 5, we created a Vector
object.
In lines 8 to 10, we added three elements, (1
,3
,5
), to the created Vector
object.
In line 14, we used the add()
method of the Vector
object to add element 2
at index 1
. Now, the vector will be 1
,2
,3
,5
.
In line 17, we used the add()
method of the Vector
object to add element 4
at index 3
. Now, the vector will be 1
,2
,3
,4
,5
.