java.util.ArrayList add(int index, E element) Method Example

The add() method of java.util.ArrayList class will simply inserts the element at the end of the list. where as add(int index, E element) method inserts the specified element at the specified position in this list.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 to list 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.Arraylist.add(index,element) method.

import java.util.ArrayList;

public class AddMethodArrayListExample 
{
	public static void main(String args[])
	{
		// create an empty array list
		ArrayList al = new ArrayList();
		
		// use add() method to add elements to the list
		al.add("Element1");
		al.add("Element2");
		al.add("Element3");
		
		//adding new element at second position 
		al.add(1,"Element4");
		
		//Printing the elements of the list
		System.out.println("Elements of the list");
		for(String temp:al)
		{
			System.out.println(temp);
		}
	}
}

Output

Elements of the list
Element1
Element4
Element2
Element3

Leave a Reply

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