ArrayDeque
A fast array-based double-ended queue — a replacement for `Stack` and `LinkedList`.
Available since: Java 1.6
Syntax
public class ArrayDeque<E> implements Deque<E>Examples
As a queue:
void main() {
Queue<String> queue = new ArrayDeque<>();
queue.offer("a");
queue.offer("b");
IO.println(queue.poll() + " " + queue.poll());
}Output:
a bAs a stack — checking brackets:
boolean balanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') stack.push(c);
else if (c == ')') {
if (stack.isEmpty()) return false;
stack.pop();
}
}
return stack.isEmpty();
}
void main() {
IO.println(balanced("(a(b)c)"));
IO.println(balanced("(()"));
}Output:
true
falseNotes
It is faster than LinkedList and the legacy Stack class. It does not accept null (NullPointerException) and is not thread-safe; for threads there are ConcurrentLinkedDeque and LinkedBlockingDeque.
See also
- Deque — A double-ended queue: elements can be added and taken at both ends.
- Queue — A queue: elements are added at the tail and taken from the head.
- Deque.push() — Pushes an element onto the top of a stack (the head of a deque).
- LinkedList — A doubly linked list that implements both `List` and `Deque`.
- PriorityQueue — A queue that always hands out the smallest (or highest-priority) element.
Related recipes
In the tutorial
- Queues and deques — Queues in Java: Queue and ArrayDeque, a stack built on Deque, the offer, poll and peek methods and the PriorityQueue.