ArrayDeque Drains From Both Ends
Consume a two-ended work queue with ArrayDeque pollFirst and pollLast, pairing entries from both sides until the deque runs empty.
Code
import java.util.ArrayDeque;
import java.util.Deque;
public class RoundRobinReconciler {
public static void main(String[] args) {
Deque<String> queue = new ArrayDeque<>();
queue.addLast("upload-a");
queue.addLast("upload-b");
queue.addLast("upload-c");
queue.addLast("upload-d");
queue.addLast("upload-e");
// 两端各取一个配对消化;元素个数为奇数时队尾先取空,
// pollLast 返回 null,所以每轮都要判空
while (!queue.isEmpty()) {
String first = queue.pollFirst();
String last = queue.pollLast();
if (last == null) {
System.out.println("pair: [" + first + "]");
} else {
System.out.println("pair: [" + first + " + " + last + "]");
}
}
// 同一个类当栈用:push/pop 都作用于队头
Deque<String> undo = new ArrayDeque<>();
undo.push("draw rect");
undo.push("fill red");
System.out.println("undo pop: " + undo.pop() + ", left: " + undo.peek());
}
}How it works
The code’s whole job belongs to the class RoundRobinReconciler and the function main.
One loop does the cycling here: while (!queue.isEmpty()).
Watch out for
- Every symbol it touches is a language built-in — nothing to fetch.
Using it
Signature: public static void main(String[] args)
Output lines are prefixed (pair: [, undo pop:), which keeps the printed trace aligned with the operations that caused it.
Key statements
Deque<String> queue = new ArrayDeque<>();
Deque<String> undo = new ArrayDeque<>();
String first = queue.pollFirst();
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does ArrayDeque Drains From Both Ends print when run?
- Running the file directly is enough — expect labeled output lines such as `pair: [`, `undo pop:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.