ConceptDifficulty: Intermediate1 min

A Collection That Decides What Comes Out Next

A job runner holds work that has not been done yet. The interesting question is not what is in the collection — it is which item the runner should pick up next, and something has to decide.

A Queue is a collection with an opinion about that. Adding is the same as ever; taking is where the decision lives.

The two queue implementations you will actually use
ClassWhat comes out firstUse it for
ArrayDequeWhatever went in first, or last, as you chooseWork in arrival order, or a stack
PriorityQueueThe smallest, by the order you supplyWork that has a priority
java
Queue<String> fifo = new ArrayDeque<>();
fifo.add("first"); fifo.add("second");
System.out.println(fifo.poll());

Queue<Integer> urgent = new PriorityQueue<>();
urgent.add(5); urgent.add(1); urgent.add(3);
System.out.println(urgent.poll());
text
first
1

Both are queues and both took three adds without complaint. The only difference is the answer to poll(), and that answer is the whole reason to choose one over the other.

ArrayDeque is a double-ended queue, so addFirst, addLast, pollFirst and pollLast let one class serve as a queue, a stack, or both at once.