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
Vectorclass is a growable array of objects. You can use an integer index to access the elements ofVector, and the size of aVectorcan 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 thevectorobject. -
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 thevectorobject. Otherwise,ArrayIndexOutOfBoundsExceptionwill 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 VectorVector<Integer> vector = new Vector<>();// add elememtsvector.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
Vectorobject. -
In lines 8 to 10: We add three elements (
10,30,50) to the created vector object. -
In line 14: We use the
insertElementAtmethod of thevectorobject to add element20at index1. Now, the vector will be[10, 20, 30, 50]. -
In line 17: We use the
insertElementAtmethod of thevectorobject to add element40at index3. Now, the vector will be[10, 20, 30, 40, 50].