Queue, Deque, Stack, Math

Queue, Deque and Stack collections plus common java.lang.Math methods.


Queue is FIFO: offer()/add() enqueue, poll()/remove() dequeue, peek()/element() inspect. Deque adds both-end operations like addFirst/addLast. ArrayDeque is a resizable-array Deque, faster than LinkedList, and works as a stack. PriorityQueue is a natural-order heap: poll() returns the smallest; null is disallowed. Legacy Stack extends Vector (push/pop/peek); Deque is preferred. java.lang.Math provides abs, max, min, pow, sqrt, random() in [0,1).

Example
int m = Math.max(3, 7);
double r = Math.random();
Video Lesson Open in new tab
Quiz
1. Which Collection interface models a first-in, first-out (FIFO) sequence?
2. Which Deque method adds an element at the front of the deque?
3. Which class is a resizable-array Deque implementation and is the recommended replacement for the legacy Stack class?
4. For a PriorityQueue using natural ordering, what does poll() return first and what about adding null?
5. Which statement about the legacy Stack class is true?
6. When the queue is empty, which behaviour of the Queue methods remove() and poll() is correct?
Coding Problems
1. Write a Java program that uses an ArrayDeque as a stack to reverse the string "Java": push each character, pop them into a StringBuilder and print the result.
Discussion

Login to join the discussion.


No comments yet.