Java Vector insertElementAt(E obj, int index) Example

We have already seen the usage of add(int index, E element) method of java.util.Vector class which will insert the specified element at the specified position in the Vector, the insertElementAt(E obj, int index) method also does the same operation inserts the specified object at the specified index

It shifts the element currently at that position to the right and the new element will added at that index.

Signature

public void insertElementAt(E obj,int index)

Inserts the specified object as a component in the vector at the specified index. Each component in the vector which is present in the vector will be shifted to the right and their index will be incremented by 1

Example

The following example shows the usage of java.util.Vector.insertElementAt(obj,index) method.

import java.util.Vector;

public class InsertElementAtMethodVectorExample 
{
	public static void main(String args[])
	{
		// Create Vector vector1 object
		Vector vector1 = new Vector();
		
		//adding elements to Vector using add()
		vector1.add("Element1");
		vector1.add("Element2");
		vector1.add("Element3");
		
		//adding "Element4" at index 1
		vector1.insertElementAt("Element4",1);
		
		//Printing the elements
		System.out.println("**Elements of the Vector**");
		for(String val : vector1)
		{
			System.out.println(val);
		}
	}
}

Output

**Elements of the Vector**
Element1
Element4
Element2
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *