What is the LinkedList.removeLastOccurrence method in Java?
A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. The data part has the value and the reference part has the address link to the next element. The elements are not indexed, so random access like an array is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedListis theimplementation of the List and Deque interfaces. The doubly-linked list A kind of linked list. Each node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. LinkedListclass is present in thejava.utilpackage.
The removeLastOccurrence method
The removeLastOccurrence method can be used to remove the last occurrence of the specified element in the LinkedList.
Syntax
public boolean removeLastOccurrence(Object o);
Parameters
This method takes the element to be removed from the list as an argument.
Return value
This method returns true if the specified element is present in the specified element.
Code
The code below demonstrates how to use the removeLastOccurrence method:
import java.util.LinkedList;class LinkedListRemoveLastOccurrenceExample {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.removeLastOccurrence("1"));System.out.println("The list is " + list);}}
Explanation
In the code above:
- In line number 1, we imported the
LinkedListclass.
import java.util.LinkedList;
- In line number 4, we created a
LinkedListobject with the namelist.
LinkedList<String> list = new LinkedList<>();
- From line number 5 to 7, we used the
addmethod of thelistobject to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
- On line number 10, we used the
removeLastOccurrencemethod to remove the last occurrence of the element"1". The element"1"is present in two indexes,0and2. After calling this method, the element at index2will be removed.
list.removeLastOccurrence("1"); // true
list; // ["1", "2"]