How to Add Element to Vector at Specified Index in Java


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:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments