A LinkedList
is a collection of linear data elements. Each element, or node, contains a data part and a reference part.
The data part has the value and the reference part has the address to the next element.
The elements are not indexed, so random access is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedList
is the doubly-linked list implementation of theList
andDeque
interfaces.
The LinkedList
class is present in the java.util
package.
removeFirstOccurrence
method of the LinkedList
class?The removeFirstOccurrence
method is used to remove the first occurrence of the specified element in the LinkedList
.
public boolean removeFirstOccurrence(Object o);
This method takes the element to be removed from the list as a parameter.
This method returns true
if the list contains the specified element. Otherwise, it returns false
.
The code below demonstrates how to use the removeFirstOccurrence
method.
import java.util.LinkedList;class LinkedListRemoveFirstOccurrenceExample {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("1");System.out.println("The list is " + list);System.out.println("Is element present " + list.removeFirstOccurrence("1"));System.out.println("The list is " + list);}}
In the above code:
LinkedList
class.import java.util.LinkedList;
LinkedList
objects with the name list
.LinkedList<String> list = new LinkedList<>();
add
method of the list
object to add three elements ("1","2","3"
) to the list.list.add("1");
list.add("2");
list.add("3");
removeFirstOccurrence
method to remove the first occurrence of the element "1"
. The element "1"
is present in two indexes, 0
and 2
. After calling this method, the element at index 0
will be removed.list.removeFirstOccurrence("1"); // true