Java Vector - add() Method
The java.util.Vector.add() method is used to insert the specified element at specified index in the vector. The method shifts the current element at the specified position (if any) and any subsequent elements to the right by adding one to their indices. Addition of new element results into increasing the vector size by one.
Syntax
public void add(int index, E element)
Here, E is the type of element maintained by the container.
Parameters
index |
Specify index number at which new element need to be inserted in the vector. |
element |
Specify element which need to be inserted in the vector. |
Return Value
void type.
Exception
Throws IndexOutOfBoundsException, if the index is out of range i.e., (index < 0 || index > size()).
Example:
In the example below, the java.util.Vector.add() method is used to insert new element at specified position in the vector.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a vector Vector<Integer> MyVector = new Vector<Integer>(); //populating vector MyVector.addElement(10); MyVector.addElement(20); MyVector.addElement(30); //inserting new element in the vector MyVector.add(1,100); System.out.println("MyVector contains: " + MyVector); //inserting new element in the vector MyVector.add(0,500); System.out.println("MyVector contains: " + MyVector); } }
The output of the above code will be:
MyVector contains: [10, 100, 20, 30] MyVector contains: [500, 10, 100, 20, 30]
❮ Java.util - Vector