Working with Queue and Deque

1. Understanding Queue Interface

MethodThrows on FailureReturns Special Value
Insertadd(e)offer(e)
Removeremove()poll()
Examineelement()peek()

2. Using PriorityQueue

Example: Priority queue

PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(5); pq.offer(1); pq.offer(3);
pq.poll();  // 1 (min-heap)

PriorityQueue<Task> byPriority =
    new PriorityQueue<>(Comparator.comparingInt(Task::priority).reversed());
PropertyDetail
OrderNatural or comparator (min-heap)
IterationNOT in priority order
Complexityoffer/poll O(log n), peek O(1)

3. Using ArrayDeque

PropertyDetail
BackingResizable circular array
NullNot allowed
UseDefault Deque/Stack/Queue choice
Faster thanStack and LinkedList

4. Using LinkedList as Queue

AspectDetail
ImplementsList, Deque, Queue
Allows nullYes
Recommended overLess than ArrayDeque (slower)

5. Using offer(), poll(), peek() Methods

MethodEmpty/Full Behavior
offer(e)Returns false if cannot insert
poll()Returns null if empty
peek()Returns null if empty

6. Understanding Deque Interface

OperationFirst-endLast-end
Insert (throws)addFirstaddLast
Insert (returns)offerFirstofferLast
Remove (throws)removeFirstremoveLast
Remove (returns)pollFirstpollLast
ExaminepeekFirstpeekLast

7. Using addFirst(), addLast() Methods

MethodThrows
addFirst(e)IllegalStateException if capacity-restricted & full
addLast(e)Same

8. Using removeFirst(), removeLast() Methods

MethodThrows
removeFirst()NoSuchElementException if empty
removeLast()NoSuchElementException if empty

9. Using Deque as Stack

Stack OpDeque Equivalent
push(e)addFirst(e)
pop()removeFirst()
peek()peekFirst()

10. Using Deque as Queue

Queue OpDeque Equivalent
offer(e)offerLast(e)
poll()pollFirst()
peek()peekFirst()