Course contentsShow
← Java
Lesson 1206 of 2,87027. Queue and Deque ImplementationsFree lesson

Examining Elements: getFirst, getLast, peekFirst, peekLast

Non-destructive methods to inspect elements at both ends without removing them.

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 (throws NoSuchElementException if empty)
  • getLast() – Returns the last element (throws NoSuchElementException if 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, or null if empty
  • peekLast() – Returns the last element, or null if empty

Use these when you want to gracefully handle an empty deque without catching exceptions.

When to Use Each

  • Use getFirst/getLast when an empty deque indicates a programming error
  • Use peekFirst/peekLast when 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.