Course contentsShow
← Java
Lesson 972 of 2,87023. Collections Framework OverviewFree lesson

Deque Interface: Double-Ended Queue Operations

Discover Deque's ability to add and remove elements from both ends, supporting stack and queue operations.

Deque Interface: Double-Ended Queue Operations

What you'll learn: How the Deque interface enables adding and removing elements from both ends, supporting both stack and queue behavior.

What Is a Deque?

A Deque (pronounced "deck") stands for Double-Ended Queue. While a regular Queue only allows you to add elements at one end and remove from the other (FIFO), a Deque lets you add or remove elements from either end. Think of it like a line of people where new arrivals can join at the front or back, and people can leave from the front or back.

Why Deque Matters

This flexibility makes Deque incredibly versatile:

  • It can behave like a queue (FIFO: First-In-First-Out)
  • It can behave like a stack (LIFO: Last-In-First-Out)
  • It can do both simultaneously in different parts of your program

Core Operations

The Deque interface provides methods for both ends:

Adding elements:

  • addFirst(e) / offerFirst(e) — insert at the head
  • addLast(e) / offerLast(e) — insert at the tail

Removing elements:

  • removeFirst() / pollFirst() — remove from the head
  • removeLast() / pollLast() — remove from the tail

Inspecting elements:

  • getFirst() / peekFirst() — view head element
  • getLast() / peekLast() — view tail element

The difference between paired methods (like removeFirst vs pollFirst) is typically exception behavior: one throws an exception on failure, the other returns null.

Stack and Queue Compatibility

Because Deque supports both ends, it can replace the legacy Stack class (using push/pop semantics) and extend Queue functionality for bidirectional processing.

Key Takeaway: The Deque interface extends queue functionality to support insertion and removal from both ends, making it suitable for implementing both stacks (LIFO) and queues (FIFO) with a single, flexible data structure.