Card 04/ 08
Queues: ArrayDeque and PriorityQueue
Adding works the same; which element poll returns is the whole reason to choose one.
A queue is a collection that decides which element comes out next. Adding is the same as for any collection; poll() takes the next element, and the queue's class decides which one that is. The two you will use are ArrayDeque, which works by arrival order, and PriorityQueue, which works by an order you supply.
A job runner holds work that has not been done yet. The question that matters is not what is in the collection but which job the runner should pick up next.
| 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 queues accepted three adds without complaint. The only difference is the answer to poll(): the first item added, or the smallest. A PriorityQueue of your own class needs that class to be Comparable, or a Comparator passed to its constructor, so it knows what "smallest" means.
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.
← → move through sections and cards