Java / Java 21 Collection Framework features Interview questions
Which is better and why: getFirst() or peekFirst() on an ArrayDeque?
Neither is universally "better" - they differ in how they handle an empty deque, so the right choice depends on whether an empty deque is an expected, normal case or a bug you want to surface loudly.
| getFirst() | peekFirst() |
Throws NoSuchElementException if empty | Returns null if empty |
| Good when an empty deque signals a bug | Good when emptiness is a normal, expected state |
From SequencedCollection/Deque | From Deque only |
In a producer-consumer queue where "nothing to process right now" is routine, peekFirst() avoids wrapping every call in a try-catch. In code where reaching this point with an empty deque indicates a logic error elsewhere, getFirst()'s exception is more useful for catching that bug immediately.
More Related questions...