What is the ArrayDeque.removeLastOccurrence method in Java?
An Deque interface.
ArrayDequecan be used as both a stack or queue.Nullelements are prohibited.
What is the removeLastOccurrence method?
The removeLastOccurrence method of the ArrayDeque class is used to remove the last occurrence of the specified element in the ArrayDeque object.
Syntax
public boolean removeLastOccurrence(Object o)
Parameter
This method takes the element to be removed from the deque as a parameter.
Return value
This method returns true if the deque contains the specified element. Otherwise, it returns false.
Code
The code below demonstrates how to use the removeLastOccurrence method.
import java.util.ArrayDeque;class ArrayDequeRemoveLastOccurrenceExample {public static void main( String args[] ) {ArrayDeque<String> arrayDeque = new ArrayDeque<>();arrayDeque.add("1");arrayDeque.add("2");arrayDeque.add("1");System.out.println("The arrayDeque is " + arrayDeque);System.out.println("Is element present & removed: " + arrayDeque.removeLastOccurrence("1"));System.out.println("The arrayDeque is " + arrayDeque);}}
Explanation
In the code above:
-
In line 1, we imported the
ArrayDequeclass. -
In line 4, we created an
ArrayDequeobject with the namearrayDeque. -
From lines 5 to 7, we used the
add()method of thearrayDequeobject to add three elements ("1","2","3") todeque. -
In line 10, we used the
removeLastOccurrencemethod to remove the last occurrence of the element"1". The element"1"is present in two indexes0and2. After calling this method, the element at index2will be removed.