Java ArrayDeque push()

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

1. ArrayDeque push() Method Overview

Definition:

The push() method of the ArrayDeque class in Java is used to push an element onto the stack represented by the ArrayDeque. This method inserts the element at the front of the ArrayDeque.

Syntax:

public void push(E e)

Parameters:

- e: The element to add.

Key Points:

- The push() method inserts the specified element at the front of the ArrayDeque.

- This method is equivalent to addFirst(E).

- The ArrayDeque class is a resizable array implementation of the Deque interface.

- ArrayDeque does not support the addition of null elements. Attempting to add null to an ArrayDeque will result in a NullPointerException.

- The ArrayDeque class is not thread-safe, so external synchronization is necessary if an ArrayDeque instance will be accessed by multiple threads concurrently.

2. ArrayDeque push() Method Example

import java.util.ArrayDeque;

public class ArrayDequeExample {

    public static void main(String[] args) {
        ArrayDeque<Integer> deque = new ArrayDeque<>();

        // Adding elements using add() method
        deque.add(1);
        deque.add(2);
        deque.add(3);

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

        // Using push() to add an element at the front
        deque.push(0);

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

        // Trying to push null to the ArrayDeque will throw NullPointerException
        try {
            deque.push(null);
        } catch (NullPointerException e) {
            System.out.println("Cannot push null to an ArrayDeque.");
        }
    }
}

Output:

Original ArrayDeque: [1, 2, 3]
ArrayDeque after push: [0, 1, 2, 3]
Cannot push null to an ArrayDeque.

Explanation:

In this example, we initialize an ArrayDeque and add some elements using the add() method. 

We then use the push() method to insert the element 0 at the front of the ArrayDeque. The state of the ArrayDeque is printed before and after the push() operation. 

Finally, we demonstrate that trying to push null to the ArrayDeque results in a NullPointerException.

Comments