insertElementAt() method of Vector class present inside java.util package is used to insert a particular element at the specified index of the Vector. Both the element and the position are passed as the parameters. If an element is inserted at a specified index, then all the elements are pushed upward by one and hence the capacity is increased, creating a space for the new element.
Syntax:
Vector.insertElementAt()
Parameters: The method accepts two parameters:
- element: It is required to be inserted into the vector.
- index: It refers to the position where the new element is to be inserted(integer type)
Exceptions Thrown: ArrayIndexOutOfBoundsException if the index is an invalid number.
Let us now add elements by proposing examples for both string elements and integer elements and applying our method over both of them just only to be familiar with the working of this method with different primitive datatypes.
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
Vector<String> vec_tor = new Vector<String>();
vec_tor.add( "Welcome" );
vec_tor.add( "To" );
vec_tor.add( "Geeks" );
vec_tor.add( "4" );
vec_tor.add( "Geeks" );
System.out.println( "Vector: " + vec_tor);
vec_tor.insertElementAt( "Hello" , 2 );
vec_tor.insertElementAt( "World" , 6 );
System.out.println( "The final vector is "
+ vec_tor);
}
}
|
Output: Vector: [Welcome, To, Geeks, 4, Geeks]
The final vector is [Welcome, To, Hello, Geeks, 4, Geeks, World]
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
Vector<Integer> vec_tor = new Vector<Integer>();
vec_tor.add( 10 );
vec_tor.add( 20 );
vec_tor.add( 30 );
vec_tor.add( 40 );
vec_tor.add( 50 );
System.out.println( "Vector: " + vec_tor);
vec_tor.insertElementAt( 100 , 0 );
vec_tor.insertElementAt( 200 , 4 );
System.out.println( "The final vector is "
+ vec_tor);
}
}
|
Output: Vector: [10, 20, 30, 40, 50]
The final vector is [100, 10, 20, 30, 200, 40, 50]