Card 04/ 08
All 8 cards
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.
| Class | What comes out first | Use it for |
|---|---|---|
ArrayDeque | Whatever went in first, or last, as you choose | Work in arrival order, or a stack |
PriorityQueue | The smallest, by the order you supply | Work that has a priority |
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());first
1Both 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.