Skip to content

peek and element in Java’s LinkedList

What is the difference between peek and element in Java’s LinkedList?

Here is what the Oracle Java Documentation page describes them to be, but they do not explain the difference.

public E peek()
Retrieves, but does not remove, the head (first element) of this list.
Specified by: peek in interface Deque<E>
Specified by: peek in interface Queue<E>
Returns: the head of this list, or null if this list is empty
Since: 1.5

public E element()
Retrieves, but does not remove, the head (first element) of this list. Specified by: element in interface Deque<E>
Specified by: element in interface Queue<E>
Returns: the head of this list
Throws: NoSuchElementException – if this list is empty
Since: 1.5

Is the difference just that one throws and exception and another returns null in case our list is empty?

Answer

Looking at the documentation of Queue, we find the following table:

Summary of Queue methods

Throws Exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()

So as we can see, the difference is that element() may throw a NoSuchElementException, while peek() does not.