Java LinkedList remove(int index) Method Example

We have already learnt about remove() methods of java.util.LinkedList class which will get us the first element(head) of the list and at the same time it will remove that element from the list. Our remove(int index) method is used to remove the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

Signature

public E remove(int index)

This method removes the element of the 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.remove(index) method.

import java.util.LinkedList;

public class RemoveMethodLinkedListExample {
	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");
		
		//Printing the elements of the list
		System.out.println("**Elements of the list before remove**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
		
		//Removing the element present at the index 1
		l.remove(1);
		
		//Printing the elements of the list
		System.out.println("**Elements of the list after remove**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

**Elements of the list before remove**
Element1
Element2
Element3
**Elements of the list after remove**
Element1
Element3

Leave a Reply

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