What is the Vector.insertElementAt method in Java?

The insertElementAt() method of the Vector class can be used to add an element at the specific index of the vector object. The index of the elements present at and after the passed index will be shifted upward, i.e., increased by 1.

The Vector class is a growable array of objects. You can use an integer index to access the elements of Vector, and the size of a Vector can be increased or decreased.

Syntax

public void insertElementAt(E obj,int index)

Parameters

This method takes two arguments:

  • obj: The element to be added to the vector object.

  • index: 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, ArrayIndexOutOfBoundsException will be thrown.

Return value

This method doesn’t return a value.

Code

import java.util.Vector;
class InsertElementAt {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vector = new Vector<>();
// add elememts
vector.add(10);
vector.add(30);
vector.add(50);
System.out.println("The Vector is: " + vector); // [10,30,50]
vector.insertElementAt(20, 1); // [10,20,30,50]
System.out.println("\nAfter calling insertElementAt(20,1). The Vector is: " + vector);
vector.insertElementAt(40, 3); // [10,20,30,40,50]
System.out.println("\nAfter calling insertElementAt(40,3). The Vector is: " + vector);
}
}

Explanation

In the code above:

  • In line 5: We create a Vector object.

  • In lines 8 to 10: We add three elements (10,30,50) to the created vector object.

  • In line 14: We use the insertElementAt method of the vector object to add element 20 at index 1. Now, the vector will be [10, 20, 30, 50].

  • In line 17: We use the insertElementAt method of the vector object to add element 40 at index 3. Now, the vector will be [10, 20, 30, 40, 50].