The Deque interface in Java is a powerful and versatile data structure that extends the Queue Interface. It represents a double-ended queue, allowing elements to be added or removed from both ends.
A Deque (pronounced "deck") is an acronym for Double Ended Queue. It supports element insertion and removal at both ends, making it a flexible choice for various scenarios in Java programming.
Operation | First Element (Head) | Last Element (Tail) |
---|---|---|
Insert | addFirst(e), offerFirst(e) | addLast(e), offerLast(e) |
Remove | removeFirst(), pollFirst() | removeLast(), pollLast() |
Examine | getFirst(), peekFirst() | getLast(), peekLast() |
Java provides two main implementations of the Deque interface:
import java.util.ArrayDeque;
import java.util.Deque;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
// Adding elements
deque.addFirst("First");
deque.addLast("Last");
deque.offerFirst("New First");
System.out.println(deque); // Output: [New First, First, Last]
// Removing elements
String first = deque.removeFirst();
String last = deque.pollLast();
System.out.println("Removed: " + first + ", " + last);
System.out.println(deque); // Output: [First]
}
}
Deques are particularly useful in scenarios where you need:
When choosing between ArrayDeque and LinkedList, consider:
The Java Deque interface provides a flexible and efficient way to work with double-ended queues. By understanding its methods and implementations, you can leverage its power in your Java applications, enhancing your ability to manage complex data structures effectively.
For more advanced Java concepts, explore Java Multithreading or Java Generics.