Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Java › Collections

Stack, queue, priority queue

Insertion order and removal order

Why it exists — If values are gathered in one list and you find which to take out each time, the rules for taking out are scattered through the code, and finding the smallest value means scanning the whole list every time. Stacks, queues, and priority queues let the data structure decide the order of removal, so that taking out the latest first, the earliest first, or the smallest first is done with one method. A priority queue uses a heap so that it does not re-sort everything when inserting and removing.

Where it's used today — A stack is used for undo history, checking matching parentheses, and depth-first search, and a queue for a waiting list of tasks to process in the order they arrived and for breadth-first search. A priority queue is used to process tasks with the nearest deadline first, to pick the top N, or to find the shortest path (Dijkstra). For a queue that several threads put into and take out of together, a BlockingQueue implementation such as LinkedBlockingQueue is used.

Even when you insert the same five numbers in the same order, the order in which they come out depends on the data structure. A stack returns the most recently inserted value first, a queue returns the earliest inserted value first, and a priority queue returns the smallest value first.

Checked against real execution · Checked against the real ArrayDeque and PriorityQueue on JDK 21

Concepts in this lab

Stack, queue, deque
A stack takes out the most recently added item first (LIFO), a queue takes out the earliest added item first (FIFO), and a deque lets you add and remove items at both ends. In Java, ArrayDeque is the recommended implementation for both stacks and queues.
Heap and priority queue
Why it exists — If values to be taken out by priority are kept in a sorted array, each insertion must shift the elements after it, which costs O(n), and if they are kept unsorted, each removal costs O(n). A heap does not sort everything; it keeps only the order in which a parent comes before its children, which makes both insertion and removal O(log n).
Where it's used today — It is used in a scheduler that picks the reserved task with the earliest run time (Java's ScheduledThreadPoolExecutor also uses a heap) and in merging several sorted lists into one. If you need to walk through everything in order, not just the first one, or to delete a value in the middle, TreeSet or TreeMap is better.
A heap is a complete binary tree in which each parent node is always less than or equal to its child nodes (a min-heap) or greater than or equal to them (a max-heap). It lets you see the smallest (or largest) value in O(1) and remove it in O(log n), so it is used to implement a priority queue. Java's PriorityQueue is implemented with a heap. It shares only its name with the heap that is a memory area of the JVM.
Time complexity (big-O notation)
Why it exists — If you measure running time in seconds, the value differs by computer and by input, so it is hard to say which of two approaches is better. Big-O notation drops constants and small terms and keeps only the shape of the growth as the input gets larger, so it lets you compare approaches regardless of the environment.
Where it's used today — It is used when choosing a data structure (contains is O(n) for ArrayList and O(1) on average for HashSet), when judging whether a double loop can withstand growing data, and when estimating whether a solution will finish in time in a coding test.
This notation shows how fast the number of operations of an algorithm grows as the input size n grows. O(1) means constant regardless of size, O(log n) means only one more step when the size doubles, O(n) means proportional to the size, and O(n²) means proportional to the square of the size. It is the basis for judging which approach holds up as the amount of data grows.

Try these

Running with the default settings

  1. offer(5): The value is placed at the end of the array and then moves up, swapping places with its parent while it is smaller than the parent. It is the first value, so it stays at the top.
  2. offer(2): The value is placed at the end of the array and then moves up, swapping places with its parent while it is smaller than the parent. It moved up 1 level and reached the top (the place of the smallest value).
  3. offer(8): The value is placed at the end of the array and then moves up, swapping places with its parent while it is smaller than the parent. It is not smaller than its parent, so it stays where it is.
  4. offer(1): The value is placed at the end of the array and then moves up, swapping places with its parent while it is smaller than the parent. It moved up 2 levels and reached the top (the place of the smallest value).
  5. offer(9): The value is placed at the end of the array and then moves up, swapping places with its parent while it is smaller than the parent. It is not smaller than its parent, so it stays where it is.
  6. poll(): Removes the smallest value, 1, from the top. The last value in the array is moved to the empty top and then moves down, swapping places with the smaller of its two children (it moved down 2 levels).
  7. poll(): Removes the smallest value, 2, from the top. The last value in the array is moved to the empty top and then moves down, swapping places with the smaller of its two children (it moved down 1 level).
  8. poll(): Removes the smallest value, 5, from the top. If any values remain, the last value in the array is moved to the empty top. This time no swap was needed.
  9. poll(): Removes the smallest value, 8, from the top. If any values remain, the last value in the array is moved to the empty top. This time no swap was needed.
  10. poll(): Removes the smallest value, 9, from the top. If any values remain, the last value in the array is moved to the empty top. This time no swap was needed.

Result of this run

Code

// Only the lines inside main are shown (class, main declaration, and imports omitted)
PriorityQueue<Integer> pq = new PriorityQueue<>();   // smaller values first
for (int x : List.of(5, 2, 8, 1, 9)) pq.offer(x);

while (!pq.isEmpty()) System.out.print(pq.poll() + " ");

Assumptions of this model

The removal order and the changes to the internal array of the priority queue were checked by running the real ArrayDeque and PriorityQueue on JDK 21 in our test environment (the internal array matched after every insertion and after every removal). By default, PriorityQueue returns the smallest value first, and you can change the ordering by supplying a Comparator.

Previous lab: Kinds of Set and Map · Next lab: Removing during iteration

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these