Java Utility Library

Java Vector - insertElementAt() Method



The java.util.Vector.insertElementAt() method is used to insert the specified object as a component in the vector at the specified index. Each component in the vector with an index greater or equal to the specified index is shifted upward to have an index one greater than the value it had previously.

The index must be a value greater than or equal to zero and less than or equal to the current size of the vector.

Syntax

public void insertElementAt(E obj, int index)

Here, E is the type of element maintained by the container.


Parameters

obj Specify the component to insert.
index Specify the index, where the new component to be inserted.

Return Value

void type.

Exception

Throws ArrayIndexOutOfBoundsException, if the index is out of range (index < 0 || index > size()).

Example:

In the example below, the java.util.Vector.insertElementAt() method is used to insert the specified element in the given vector.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVec = new Vector<Integer>();

    //populating vector
    MyVec.add(10);
    MyVec.add(20);
    MyVec.add(30);
    
    //print the content of the vector
    System.out.println("MyVec contains: " + MyVec);

    //insert elements in the vector
    MyVec.insertElementAt(100, 0);
    MyVec.insertElementAt(200, 1);

    //print the content of the vector
    System.out.println("MyVec contains: " + MyVec);    
  }
}

The output of the above code will be:

MyVec contains: [10, 20, 30]
MyVec contains: [100, 200, 10, 20, 30]

❮ Java.util - Vector