Command Palette

Search for a command to run...

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

Queue methods: offer, poll, peek vs add, remove, element

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.

Queue methods: offer, poll, peek vs add, remove, element
Sign in to run this example in your browser.

Expected output

queue: [asha, ravi, meera], next up: asha
served asha
served ravi
served meera
poll on empty: null
peek on empty: null
element on empty: NoSuchElementException