Examining Elements: getFirst, getLast, peekFirst, peekLast
What you'll learn: How to inspect elements at both ends of an ArrayDeque without removing them.
The Core Idea
Sometimes you need to see what's at the front or back of your deque without actually taking it out. ArrayDeque gives you non-destructive inspection methods that let you peek at elements while leaving the deque unchanged.
Think of it like looking at the first or last person in a line without asking them to step out. You're just checking who's there.
Two Flavors of Inspection
Exception-Throwing Methods: getFirst and getLast
These methods return the element at the specified end, but throw an exception if the deque is empty:
getFirst()– Returns the first element (throwsNoSuchElementExceptionif empty)getLast()– Returns the last element (throwsNoSuchElementExceptionif empty)
Use these when you're confident the deque has elements and want to fail fast if it doesn't.
Null-Returning Methods: peekFirst and peekLast
These methods return the element at the specified end, but return null if the deque is empty:
peekFirst()– Returns the first element, ornullif emptypeekLast()– Returns the last element, ornullif empty
Use these when you want to gracefully handle an empty deque without catching exceptions.
When to Use Each
- Use
getFirst/getLastwhen an empty deque indicates a programming error - Use
peekFirst/peekLastwhen an empty deque is a normal, expected condition you need to check for
All four methods have O(1) constant time performance since ArrayDeque maintains references to both ends.
Key Takeaway: Use getFirst/getLast for exception-based checking or peekFirst/peekLast for null-based checking to inspect deque ends without modifying the structure.