Stack: last in, first out
Think of it like this: A stack of plates: you put new plates on top and take from the top. The last plate added is the first one used.
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) {
ArrayDeque<String> stack = new ArrayDeque<>();
stack.push("page1");
stack.push("page2");
stack.push("page3");
System.out.println("Top: " + stack.peek());
System.out.println("Back to: " + stack.pop());
System.out.println("Back to: " + stack.pop());
System.out.println("Left: " + stack);
}
}Output
Top: page3 Back to: page3 Back to: page2 Left: [page1]
Your browser's Back button works like a stack of pages you visited.
Queue: first in, first out
Think of it like this: A queue at a ticket counter: the first person to arrive is the first one served.
import java.util.ArrayDeque;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<String> line = new ArrayDeque<>();
line.offer("Asha");
line.offer("Ravi");
line.offer("Meera");
while (!line.isEmpty()) {
System.out.println("Serving " + line.poll());
}
}
}Output
Serving Asha Serving Ravi Serving Meera
| Stack | Queue | Meaning |
|---|---|---|
push(x) | offer(x) | add |
pop() | poll() | take out and remove |
peek() | peek() | look at the next item without removing it |
PriorityQueue: the most important first
A PriorityQueue always gives you the smallest item first (or whatever order you choose), no matter when it was added:
import java.util.Collections;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30);
pq.add(5);
pq.add(18);
while (!pq.isEmpty()) {
System.out.print(pq.poll() + " ");
}
System.out.println();
PriorityQueue<Integer> biggestFirst = new PriorityQueue<>(Collections.reverseOrder());
biggestFirst.add(30);
biggestFirst.add(5);
biggestFirst.add(18);
System.out.println(biggestFirst.poll());
}
}Output
5 18 30 30
Tip: Java also has an old
Stackclass and aLinkedListthat can act as a queue.ArrayDequeis the modern, faster choice for both.