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

The add() method of java.util.LinkedList 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.LinkedList.add(index,element) method.

import java.util.LinkedList;

public class AddMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the list
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		
		//adding new element at second position 
		l.add(1,"Element4");
		
		//Printing the elements of the list
		System.out.println("Elements of the list");
		for(String temp:l)
		{
			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 *