Java ArrayDeque
Java ArrayDeque
An ArrayDeque is a special type of queue that lets you add or remove elements
from both the front and the back.
The word "Deque" stands for Double-Ended Queue. This means you can treat it like a line where people can join or leave from either end.
It is part of the java.util package and implements both the
Queue and
Deque interfaces.
Tip: ArrayDeque is faster than
LinkedList and has no size limit.
Create an ArrayDeque
Example
Create an ArrayDeque object called cars that will store Strings:
import java.util.ArrayDeque;
ArrayDeque<String> cars = new ArrayDeque<>();
Now you can use methods like add() and addFirst() to add to the front,
addLast() to add to the back,
and poll() to remove items.
Add Items
You can add elements at the front or back of the deque:
Example
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) {
ArrayDeque<String> cars = new ArrayDeque<>();
cars.add("Volvo"); // Add to back by default
cars.addFirst("Mazda"); // Add to front
cars.addLast("BMW"); // Add to back
System.out.println(cars);
}
}
Remove Items
You can remove elements from the front or back of the deque:
Example
cars.poll(); // Removes first element (same as pollFirst())
cars.pollFirst(); // Removes from the front
cars.pollLast(); // Removes from the back
Peek at Elements
Use peek() to look at elements without removing them:
Example
cars.peek(); // Looks at the first element
cars.peekFirst(); // Same as peek()
cars.peekLast(); // Looks at the last element
Loop Through an ArrayDeque
Use a for-each loop to go through all elements:
When to Use ArrayDeque?
Use ArrayDeque when you need a fast and flexible way to add or remove elements from both ends of a queue.
- When you want a better alternative to
LinkedListfor queues and stacks - When you don't need to access elements by index (like in a
List)