Skip to the workspace
Pebellslearn by building
Collections  ›  Capstone Project

Queue, Deque and Stack

Queue 14 minA queue removes elements in the order they were added, a stack removes the most recently added first, and ArrayDeque supports both by allowing access at either end.

java / Queue, Deque and Stack

Explore each scene at your own pace.

01 · The rule

The rule

Queue, Deque and Stack

A queue removes elements in the order they were added, a stack removes the most recently added first, and ArrayDeque supports both by allowing access at either end.

Choose first-in-first-out or last-in-first-out behavior through the appropriate collection.

At Brew Bar, customers are served in the order they arrive, while the barista's "undo" button removes the item added most recently. Those are opposite orders: first in, first out versus last in, first out. Java covers both with one flexible class.

The rule

A queue serves the oldest first; a stack serves the newest first.

A queue is FIFO: first in, first out, like the line at the counter. The Queue interface names the operations:

Queue<String> line = new ArrayDeque<>();
line.offer("Asha");       // join the back
line.offer("Ben");
line.offer("Chen");
System.out.println(line.peek());   // Asha: look at the front, keep her
System.out.println(line.poll());   // Asha: serve and remove her
System.out.println(line);          // [Ben, Chen]

A stack is LIFO: last in, first out, like a pile of clean cups where you take the top one. Undo history works the same way:

Deque<String> undo = new ArrayDeque<>();
undo.push("Latte");
undo.push("Muffin");
undo.push("Scone");
System.out.println(undo.pop());    // Scone: the last thing added
System.out.println(undo.peek());   // Muffin: now on top

A Deque (double-ended queue, said "deck") allows adding and removing at both ends, with methods like offerFirst, offerLast, pollFirst and pollLast. That is why one class, ArrayDeque, serves as both a queue and a stack. Java also has an old Stack class, but its own documentation recommends a Deque instead, so prefer ArrayDeque in new code.

On an empty collection, the methods split into two families:

Action Returns a special value Throws an exception
look at the front peek() gives null element()
remove the front poll() gives null remove(), pop()

ArrayDeque does not accept null elements, so a null from poll always means "empty".

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.