What is the ArrayDeque.remove(Object o) method in Java?

An ArrayDequeArray Double Ended Queue 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 Deque interface. ArrayDeque can 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 ArrayDeque class.

  • In line number 4: We have created an ArrayDeque object with the name arrayDeque.

  • From line numbers 5 to 7: We have used the add() method of the arrayDeque object to add three elements (1, 2, 3) to deque.

  • In line number 10: We have used the remove 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.

  • In line number 13: We have used the remove method to remove the first occurrence of the element 4. The element 4 is not present, so this method returns false.

Free Resources