Java ArrayDeque Methods Example

In this source code example, you will learn a few important Java ArrayDeque class methods with examples.

ArrayDeque (Array Double-Ended Queue) is a resizable array implementation of the Deque interface. It is part of the Java Collections Framework and resides in the java.util package.

Java ArrayDeque Important Methods Example

import java.util.ArrayDeque;

public class ArrayDequeDemo {
    public static void main(String[] args) {
        // 1. Initialization
        ArrayDeque<Integer> deque = new ArrayDeque<>();
        System.out.println("Initialized deque: " + deque);

        // 2. Adding elements
        deque.add(10);      // adds at the end
        deque.addFirst(5);  // adds at the beginning
        deque.addLast(15);  // adds at the end
        System.out.println("After adding elements: " + deque);

        // 3. Peek elements (without removal)
        System.out.println("First element (without removal): " + deque.peekFirst());
        System.out.println("Last element (without removal): " + deque.peekLast());

        // 4. Removing elements
        deque.removeFirst(); // removes the first element
        deque.removeLast();  // removes the last element
        System.out.println("After removing elements: " + deque);
    }
}

Output:

Initialized deque: []
After adding elements: [5, 10, 15]
First element (without removal): 5
Last element (without removal): 15
After removing elements: [10]

Explanation:

1. An empty ArrayDeque of type Integer is created.

2.add(10) adds the integer 10 to the end of the deque.

3. addFirst(5) adds the integer 5 to the beginning of the deque.

4. addLast(15) adds the integer 15 to the end of the deque.

5. peekFirst() retrieves the first element without removing it from the deque.

6. peekLast() retrieves the last element without removing it from the deque.

7. removeFirst() removes and returns the first element from the deque.

8. removeLast() removes and returns the last element from the deque.


Comments