Stacks and Queues with ArrayDeque

One class, two behaviours: push/pop for last-in-first-out, offer/poll for first-in-first-out.

Java · intermediate · 7 min · 12 steps · free

What you'll learn

StackQueueDemo.java

import java.util.ArrayDeque;
import java.util.Deque;

public class StackQueueDemo {
    public static void main(String[] args) {
        Deque<String> stack = new ArrayDeque<>();   // last in, first out
        stack.push("page1");
        stack.push("page2");
        stack.push("page3");
        String back = stack.pop();                   // takes the newest

        Deque<String> queue = new ArrayDeque<>();   // first in, first out
        queue.offer("ana");
        queue.offer("ben");
        String served = queue.poll();                // takes the oldest
        String next = queue.peek();                  // looks without removing
        System.out.println(back + " " + stack + " " + served + " " + next);
    }
}

Step by step

  1. A Deque used as a stack, like the back button's history.
  2. Line runs: stack.push("page1").
  3. Line runs: stack.push("page2").
  4. page3 is now on top.
  5. pop takes the newest: page3.
  6. A second Deque, used as a queue: first in, first out (FIFO).
  7. Line runs: queue.offer("ana").
  8. Line runs: queue.offer("ben").
  9. poll takes the oldest: ana was first in line.
  10. peek looks at the next item without removing it.
  11. It prints page3 [page2, page1] ana ben.
  12. page3 came off the stack (newest first); ana left the queue (oldest first).

Common mistakes

Best practices

Key takeaways

Check yourself

Push 1, 2, 3 then pop. Result?

Answer: 3. Last in, first out.

Offer 1, 2, 3 then poll. Result?

Answer: 1. First in, first out.

·

More in The Collections Framework