Video in progress
What is the difference between a Stack and a Queue, and which class is best to use for them in Java?
A stack is last in, first out (LIFO); a queue is first in, first out (FIFO). ArrayDeque is recommended for both; the old Stack class is synchronized and outdated.
📖 Answer
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2);
stack.pop(); // 2
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(1); queue.offer(2);
queue.poll(); // 1
Where each one turns up: a stack is for bracket checking, "go back", replacing recursion with a loop, and DFS. A queue is for BFS and for processing tasks in the order they arrive.
Why not java.util.Stack? It extends Vector, every method is synchronized, and it lets you modify the middle by index, which goes against the idea of a stack. LinkedList works too, but it allocates a node object for every element.
A small difference: ArrayDeque doesn't accept null. On an empty queue poll() returns null, while remove() throws an exception, so use whichever you've deliberately chosen.
Sign up to mark studied questions and save your progress.