Java.Collections.Compare the interfaces of Queue and Deque

Let’s dive into the interfaces Queue and Deque in Java — both are part of the java.util package and extend the Collection interface, but they have different purposes and capabilities.


🔷 Queue Interface

  • A FIFO (First-In-First-Out) structure.
  • Used for holding elements prior to processing.
  • Think of it like a line at the supermarket.

🔑 Common Methods in Queue:

MethodDescription
add(e)Inserts element; throws if full (rare in Java)
offer(e)Inserts element; returns false if fails
remove()Removes and returns head; throws if empty
poll()Removes and returns head; returns null if empty
element()Returns head without removing; throws if empty
peek()Returns head without removing; returns null if empty

🔶 Deque Interface (extends Queue)

  • Stands for Double-Ended Queue.
  • Can be used as:
    • A FIFO Queue (like Queue)
    • A LIFO Stack (like Stack)
  • Think of it like a deck of cards: you can add/remove from both ends.

🔑 Additional Methods in Deque:

GroupMethodDescription
Front addaddFirst(e)Adds to front
Back addaddLast(e)Adds to back
Front removeremoveFirst()Removes from front
Back removeremoveLast()Removes from back
Front peekpeekFirst()Peeks at front
Back peekpeekLast()Peeks at back
OfferofferFirst(e), offerLast(e)Adds with failure handling
PollpollFirst(), pollLast()Removes with null on empty

✅ Summary Table

FeatureQueueDeque
FIFO behavior✅ Yes✅ Yes
LIFO behavior❌ No✅ Yes (push/pop)
Add/remove at both ends❌ No✅ Yes
Common implementationsLinkedList, PriorityQueue, ArrayBlockingQueueArrayDeque, LinkedList
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.