Command Palette

Search for a command to run...

Back to the lesson: Topic 9.7 — Queue, Deque and ArrayDeque
Core Java · Example 3 of 4

Build a circular buffer and watch it wrap

head == tail means either empty or full, which is why the size counter is needed. ArrayDeque avoids the ambiguity by growing before it fills completely.

A Queue hands elements out in arrival order (first in, first out); a Deque works at both ends, so it can also be a stack (last in, first out). ArrayDeque, a circular array, is the fastest general implementation of both and replaces Stack and, for queues, LinkedList.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Simulate a printer queue: jobs "report", "photo", "invoice" arrive; print them in arrival order using an ArrayDeque as a queue, printing "printing <job>" for each.

02

Reverse the words of "java is fun" using an ArrayDeque as a stack.

03

Implement BFS on this graph and print the visiting order from node 0: edges 0-1, 0-2, 1-3, 2-3, 3-4 (an adjacency list of List<List<Integer>>).

Explain it without notes

01

What is the difference between offer/poll/peek and add/remove/element?

02

How does ArrayDeque achieve O(1) operations at both ends?

03

Why should you use ArrayDeque instead of Stack and LinkedList?

04

Explain the monotonic deque technique for sliding window maximum and its complexity.

Build a circular buffer and watch it wrap
Sign in to run this example in your browser.

Expected output

full:      head=0 tail=0 size=4, offer 50? false
poll 10, poll 20 -> head=2 tail=0 size=2
wrapped:   head=2 tail=2 size=4
drain: 30 40 50 60 -> head=2 tail=2 size=0