Java LinkedList remove(Object o) Example

The removeFirst() method of java.util.LinkedList class will get us the first element(head) of the list and at the same time it will remove that element from the list whereas remove(Object o) method will remove the first occurrence of the element from the list if it is present. If the element is not present then it leaves the list untouched

Signature

public boolean remove(Object o)

This method removes the first occurrence of the element of the list and returns true if the removal was successful.

Example

The following example shows the usage of java.util.LinkedList.remove(o) method.

import java.util.LinkedList;

public class RemoveObjectLinkedListExample {
	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 "Element1" from the list
		boolean flag = l.remove("Element2");
		System.out.println("Is the removal successful ?? "+flag);
		
		//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
Is the removal successful ?? true
**Elements of the list after remove**
Element1
Element3

Leave a Reply

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