Java Vector add(int index, E element) Method Example

We have already seen the usage of add(E e) method of java.util.Vector class which inserts the specified element to the end of the Vector, whereas add(int index, E element) will insert the specified element at the specified position in the Vector.

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

Signature

public void add(int index, E element)

This method appends the specified element at the given index and will throw “java.lang.IndexOutOfBoundsException”  if the index is out of range.

Example

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

import java.util.Vector;

public class VectorExample 
{
	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.add(1,"Element4");
		
		//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 *