What is the vector.add(index, element) method in Java?
The add() method of the Vector class can be used to add an element at the specific index of a Vector object. The index of the elements present at and after the passed index will be shifted upwards (increased by 1).
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index, and the size of aVectorcan be increased or decreased. Read more aboutVectorhere.
Syntax
public void add(int index,E element)
Function arguments
This method takes two arguments, which are as follows:
- The
indexat which the new element is to be added. Theindexshould be positive and less than or equal to the size of theVectorobject. Otherwise, theArrayIndexOutOfBoundsExceptionerror will be thrown.
index >= 0 && index <= size()
- The
elementto be added to theVectorobject.
Return value
This method doesn’t return any value.
Code
import java.util.Vector;class Add {public static void main( String args[] ) {// Creating VectorVector<Integer> vector = new Vector<>();// add elememtsvector.add(1);vector.add(3);vector.add(5);System.out.println("The Vector is: " + vector); // [1,3,5]vector.add(1, 2); // [1,2,3,5]System.out.println("\nAfter calling vector.add(1,2). The Vector is: " + vector);vector.add(3, 4); // [1,2,3,4,5]System.out.println("\nAfter calling vector.add(3,4). The Vector is: " + vector);}}
Please click the “Run” button above to see how the add() method works.
Explanation
-
In line 5, we created a
Vectorobject. -
In lines 8 to 10, we added three elements, (
1,3,5), to the createdVectorobject. -
In line 14, we used the
add()method of theVectorobject to add element2at index1. Now, the vector will be1,2,3,5. -
In line 17, we used the
add()method of theVectorobject to add element4at index3. Now, the vector will be1,2,3,4,5.