Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
A browser back button pops java-basics first, a waiting room polls Emma first, and an emergency room treats Ravi with urgency 1 before Meera and Emma. One question, who goes first, answered by an ArrayDeque used two ways and a PriorityQueue with a comparator.
What you will learn
- Use an ArrayDeque as a stack with push, peek and pop
- Use an ArrayDeque as a queue with offer, peek and poll
- Explain how one ArrayDeque does both jobs with its two ends
- Hand out the most urgent item first with a PriorityQueue and a comparator
Before you start
- From arrays to collections: the framework map
- Java sorting with Comparable and Comparator
Stacks, queues and priority queues all answer one question: who goes first? A browser back button, a waiting room and an emergency room each answer it differently.
A stack: last in, first out
package org.studyeasy.s04l11;
import java.util.ArrayDeque;
import java.util.Deque;
public class Ex01_StackWithDeque {
public static void main(String[] args) {
// Last in, first out: the browser's back button
Deque<String> history = new ArrayDeque<>();
history.push("home"); // the newest page goes on top
history.push("courses");
history.push("java-basics");
System.out.println("History: " + history);
System.out.println("Viewing: " + history.peek()); // look only
System.out.println("Back from " + history.pop()); // remove
System.out.println("Now viewing: " + history.peek());
}
}
History: [java-basics, courses, home]
Viewing: java-basics
Back from java-basics
Now viewing: courses
The naming is a little confusing: to make a stack, you create a Deque and initialise it with new ArrayDeque. push puts a page on top, so home went in first but prints last. peek only looks at the top; nothing leaves. pop removes the top, and courses is on top again. A Deque has no index, so history.get(1) is "cannot find symbol".
A queue: first in, first out
// First in, first out: the waiting room
Queue<String> waiting = new ArrayDeque<>();
waiting.offer("Emma"); // join at the back
waiting.offer("Ravi");
waiting.offer("Meera");
System.out.println("Waiting: " + waiting);
System.out.println("Next up: " + waiting.peek()); // look only
System.out.println("Seeing " + waiting.poll()); // remove
System.out.println("Seeing " + waiting.poll()); // the next one
System.out.println("Left: " + waiting);
Waiting: [Emma, Ravi, Meera]
Next up: Emma
Seeing Emma
Seeing Ravi
Left: [Meera]
Same class, opposite order. offer joins at the back, poll takes from the front, so whoever waited longest is seen first. An ArrayDeque refuses null: waiting.offer(null) throws a NullPointerException.
Two ends, two ways to use it
An ArrayDeque ("deque" is a double-ended queue) has a front and a back. As a stack, push adds at the front and pop takes from the same end, so Kiran goes in and comes straight back out. As a queue, offer adds Asha behind Meera and poll takes Emma from the front.
A PriorityQueue: most urgent first
package org.studyeasy.s04l11;
public class Patient {
private final String name;
private final int urgency; // 1 = most urgent
public Patient(String name, int urgency) {
this.name = name;
this.urgency = urgency;
}
public int getUrgency() {
return urgency;
}
@Override
public String toString() {
return name + " (urgency " + urgency + ")";
}
}
// Lower urgency number is treated first
Comparator<Patient> byUrgency = new Comparator<Patient>() {
@Override
public int compare(Patient a, Patient b) {
return Integer.compare(a.getUrgency(), b.getUrgency());
}
};
Queue<Patient> triage = new PriorityQueue<>(byUrgency);
triage.offer(new Patient("Emma", 3)); // strained ankle
triage.offer(new Patient("Ravi", 1)); // chest pain
triage.offer(new Patient("Meera", 2)); // high fever
while (!triage.isEmpty()) {
System.out.println("Treating " + triage.poll());
}
Treating Ravi (urgency 1)
Treating Meera (urgency 2)
Treating Emma (urgency 3)
In an emergency room, arrival order isn't what you want. Emma arrived first with a strained ankle, which can wait. A Patient is our own object, so Java doesn't know how to compare two of them; the comparator says the lower number is more urgent. poll always hands out the most urgent one: Ravi, then Meera, then Emma. Create the PriorityQueue without the comparator and you get a ClassCastException, because Java still can't order a Patient.
Which one for which job
| Stack | Queue | PriorityQueue | |
|---|---|---|---|
| Built with | ArrayDeque | ArrayDeque | PriorityQueue |
| Methods | push, peek, pop | offer, peek, poll | offer, poll |
| Comes out first | newest | oldest | most urgent |
| Everyday example | back button | waiting room | emergency room |
An AI can write this code for you, but you need to know these tools exist so you can decide who goes first.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java equals and hashCode: Why a HashSet Needs Both
== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.
From Arrays to Collections: The Java Collections Framework Map
An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.
Java Wrapper Classes and Autoboxing
List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.
Java ArrayList: The Stretchy Array
add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.
