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 ofVector
, and the size of aVector
can be increased or decreased.
public void insertElementAt(E obj,int index)
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.
This method doesn’t return a value.
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);}}
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]
.