What is the ArrayDeque.remove(Object o) method in Java?
An
is a growable array that allows us to add or remove an element from both the front and back. This class is the implementation class of the ArrayDeque Array Double Ended Queue Dequeinterface.ArrayDequecan be used as both a stack or a queue. Null elements are prohibited.
The remove(Object o) method
The remove method is used to remove the first occurrence of the specified element in the ArrayDeque object. If the element is not present, then no action is performed.
Syntax
public boolean remove(Object o)
Parameters
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, false is returned.
Code
The below code demonstrates how to use the remove method.
import java.util.ArrayDeque;class ArrayDequeRemoveExample {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 1 present & removed: " + arrayDeque.remove("1"));System.out.println("The arrayDeque is " + arrayDeque);System.out.println("\nIs element 4 present & removed: " + arrayDeque.remove("4"));System.out.println("The arrayDeque is " + arrayDeque);}}
Explanation
In the above code:
-
In line number 1: We have imported the
ArrayDequeclass. -
In line number 4: We have created an
ArrayDequeobject with the namearrayDeque. -
From line numbers 5 to 7: We have used the
add()method of thearrayDequeobject to add three elements (1, 2, 3) todeque. -
In line number 10: We have used the
removemethod to remove the first occurrence of the element1. The element1is present in two indexes,0and2. After calling this method, the element at index0will be removed. -
In line number 13: We have used the
removemethod to remove the first occurrence of the element4. The element4is not present, so this method returnsfalse.