Java ArrayDeque poll()

In this guide, you will learn about the ArrayDeque poll() method in Java programming and how to use it with an example.

1. ArrayDeque poll() Method Overview

Definition:

The poll() method of the ArrayDeque class in Java retrieves and removes the head (first element) of this deque, or returns null if this deque is empty. It is a non-blocking method and serves as a more flexible and exception-free alternative to the remove() method for deque implementations.

Syntax:

public E poll()

Parameters:

The method does not take any parameters.

Key Points:

- The poll() method retrieves and removes the head of the deque.

- If the deque is empty, it returns null.

- This method does not throw any exception if the deque is empty, unlike the remove() method which throws a NoSuchElementException.

- ArrayDeque class in Java implements the Deque interface and can be used as a queue (FIFO) or a stack (LIFO).

- The ArrayDeque is resizable array implementation and is not thread-safe.

2. ArrayDeque poll() Method Example

import java.util.ArrayDeque;

public class ArrayDequeExample {

    public static void main(String[] args) {

        ArrayDeque<Integer> deque = new ArrayDeque<>();

        // Adding elements to the ArrayDeque
        deque.add(1);
        deque.add(2);
        deque.add(3);

        // Printing the original ArrayDeque
        System.out.println("Original ArrayDeque: " + deque);

        // Using poll() to retrieve and remove the head of the ArrayDeque
        Integer polledElement = deque.poll();

        // Printing the polled element
        System.out.println("Polled Element: " + polledElement);

        // Printing the ArrayDeque after poll operation
        System.out.println("ArrayDeque after poll: " + deque);

        // Trying to poll from an empty ArrayDeque
        deque.clear();
        System.out.println("Polled Element from an empty ArrayDeque: " + deque.poll());
    }
}

Output:

Original ArrayDeque: [1, 2, 3]
Polled Element: 1
ArrayDeque after poll: [2, 3]
Polled Element from an empty ArrayDeque: null

Explanation:

In this example, we first create an ArrayDeque and add some elements to it. 

We then use the poll() method to retrieve and remove the head of the deque, printing both the polled element and the state of the ArrayDeque after the poll operation. 

Lastly, we attempt to poll an element from an empty ArrayDeque to demonstrate that the poll() method returns null in such cases without throwing an exception.

Comments