What is the ArrayDeque.remove method in Java?

The remove() method of the ArrayDeque class can be used to get and remove the headfirst element of the ArrayDeque object.

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 Queue. Null elements are prohibited.

Syntax

public E remove()

Parameters

This method doesn’t take any arguments.

Return value

This method retrieves and removes the head (the first element) of the ArrayDeque object. If the object is empty, then NoSuchElementException is thrown.

This method is the same as the poll method, except the poll method doesn’t throw NoSuchElementException if the deque is empty.

Code

The code below demonstrates how to use the remove method.

import java.util.ArrayDeque;
class Remove {
public static void main( String args[] ) {
ArrayDeque<String> arrayDeque = new ArrayDeque<>();
arrayDeque.add("1");
arrayDeque.add("2");
arrayDeque.add("3");
System.out.println("The arrayDeque is " + arrayDeque);
System.out.println("arrayDeque.remove() returns : " + arrayDeque.remove());
System.out.println("The arrayDeque is " + arrayDeque);
}
}

Explanation

In the code above:

  • In line number 1, we import the ArrayDeque class.

  • In line number 4, we create an ArrayDeque object with the name arrayDeque.

  • From line numbers 5 to 7, we use the add() method of the arrayDeque object to add three elements ("1","2","3") to deque.

  • On line number 10, we use the remove() method of the arrayDeque object to get and remove the head of the deque object. In our case, 1 is removed and returned.

Free Resources