Search code examples
javacollectionsarraydeque

What happens when using push(), offer() and add() methods in ArrayDeque at the same time?


ArrayDeque has methods for stacks and queues. Mostly used stack and queue methods are the ones in the below:

Stack methods: push/poll/peek

Queue methods: push/poll/peek

The thing that I've done in the below code block is that, I tried to understand behavior of the ArrayDeque when both offer, push and add methods are used in the same object. The code that I wrote and its output is given below. What is the behavior of the ArrayDeque after calling push() method, which it assumes itself as a stack, and then calling the offer() method, which is stated as queue methods.

Deque<Integer> arrayDeque = new ArrayDeque<>(); 

arrayDeque.add(3);
arrayDeque.push(4);
arrayDeque.offer(6);
arrayDeque.addFirst(2);
arrayDeque.addLast(5);
arrayDeque.addFirst(1);
System.out.println("ArrayDeque: " + arrayDeque.toString());

The output is:

ArrayDeque: [1, 2, 4, 3, 6, 5]

Solution

  • Here is what it does step by step

    // Add 3 at the tail of this deque
    arrayDeque.add(3); -> [3]
    // Add 4 at the head of this deque
    arrayDeque.push(4); -> [4, 3]
    // Add 6 at the tail of this deque
    arrayDeque.offer(6); -> [4, 3, 6]
    // Add 2 at the head of this deque
    arrayDeque.addFirst(2); -> [2, 4, 3, 6]
    // Add 5 at the tail of this deque
    arrayDeque.addLast(5); -> [2, 4, 3, 6, 5]
    // Add 1 at the head of this deque
    arrayDeque.addFirst(1); -> [1, 2, 4, 3, 6, 5]
    

    Keep in mind that the main purpose of a Deque unlike a Queue or a Stack is to have the ability to access/add the elements at/to both ends (head and tail).