Video in progress
In Queue, what is the difference between offer/poll/peek and add/remove/element?
Throws an exception / Returns a special value — Insert: add(e) / offer(e) → false; Take from the head: remove() / poll() → null; Look at the head: element() / peek() → null
📖 Answer
| Operation | Throws an exception | Returns a special value |
|---|---|---|
| Insert | add(e) |
offer(e) → false |
| Take from the head | remove() |
poll() → null |
| Look at the head | element() |
peek() → null |
Queue<String> q = new ArrayDeque<>();
q.poll(); // null
q.remove(); // NoSuchElementException
In an unbounded queue (ArrayDeque, LinkedList) offer almost always returns true. The difference shows up in a bounded queue: when an ArrayBlockingQueue is full, add throws an IllegalStateException, while offer quietly returns false.
I usually use offer/poll and check the result, which makes the code clearer. One more thing: putting a null element into a queue is a bad idea, because the null from poll() gets confused with "empty". ArrayDeque does not allow it at all.
Sign up to mark studied questions and save your progress.