In this example, we may see how to add an element at specified index of java Vector object with add method.
Source Code
package com.beginner.examples;
import java.util.Vector;
public class AddElementToSpecifiedIndexVector {
public static void main(String[] args) {
//create Vector.
Vector vector = new Vector();
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
/*
* To add an element at the specified index of Vector use add(int index, Object obj) method.
*/
vector.add(1,"X");
System.out.println("After add an element X to vector, vector contains :");
for(int index=0; index < vector.size() ; index++) {
System.out.println(vector.get(index));
}
}
}
Output:
After add an element X to vector, vector contains :
A
X
B
C
D
References
Imported packages in Java documentation: