What is the vector.add(index, element) method in Java?

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 of Vector can be accessed using an integer index, and the size of a Vector can be increased or decreased. Read more about Vector here.

Syntax

public void add(int index,E element)

Function arguments

This method takes two arguments, which are as follows:

  1. The 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()

  1. The element to be added to the Vector object.

Return value

This method doesn’t return any value.

Code

import java.util.Vector;
class Add {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vector = new Vector<>();
// add elememts
vector.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.

Explanation

  • 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.

Free Resources