ArrayDeque Stack And Queue Operations
Serve both LIFO and FIFO flows from one ArrayDeque: push/pop for undo stacks, offer/poll for queues, plus first/last access on both ends.
Code
import java.util.ArrayDeque;
import java.util.Deque;
public class UndoHistory {
public static void main(String[] args) {
// 当栈用:LIFO,push/pop 都在头部;比 java.util.Stack 与 LinkedList 更快
Deque<String> undoStack = new ArrayDeque<>();
undoStack.push("type hello");
undoStack.push("select word");
undoStack.push("delete word");
System.out.println("pop: " + undoStack.pop()); // delete word(后进先出)
System.out.println("peek: " + undoStack.peek()); // select word(只看不取)
// 当队列用:FIFO,offer 尾部进、poll 头部出
Deque<String> printQueue = new ArrayDeque<>();
printQueue.offer("job-a");
printQueue.offer("job-b");
System.out.println("poll: " + printQueue.poll()); // job-a
System.out.println("poll: " + printQueue.poll()); // job-b
// 双端能力:两端都能进出,取两端只看不动
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("mid");
deque.addLast("end");
deque.addFirst("start");
System.out.println("first: " + deque.getFirst() + " last: " + deque.getLast());
System.out.println("size: " + deque.size());
}
}How the snippet works
ArrayDeque Stack And Queue Operations keeps everything in the class UndoHistory and the function main.
Applying it
Entry signature: public static void main(String[] args)
Running the file prints labeled results such as pop:, peek:, poll: — each operation’s effect is visible in the output.
Statements that matter
Deque<String> printQueue = new ArrayDeque<>();
Deque<String> undoStack = new ArrayDeque<>();
Deque<String> deque = new ArrayDeque<>();
Interactive Tools for This Topic
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.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 Stack And Queue Operations print when run?
- No setup needed: run the file and look for labeled lines like `pop:`, `peek:`, `poll:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.