Search code examples
javalinked-list

What is the difference between getFirst() and peekFirst() in Java's LinkedList?


In Java's LinkedList implementation, I see two methods which seems to me like having identical functions.

getFirst() --Returns the first element in this list.

peekFirst() --Retrieves, but does not remove, the first element of this list, or returns null if this list is empty.

Both of them get the pointer to the First element in the LinkedList without making any changes to it. Then, what's the difference ?

The only difference I see is that peekFirst returns null if the list is empty and getFirst throws a NoSuchElementException if the list is empty. What was the use of such a design pattern ?


Solution

  • Java introduced LinkedList in version 1.2. This is when the getFirst method has been provided. This message threw NoSuchElementException when the list is empty, causing programmers to do an extra check before the call:

    Element e = null;
    if (!myList.isEmpty()) {
         e = myList.getFirst();
    }
    

    This was an inconvenience, which has been fixed in Java version 1.6 by adding the peekFirst method and other methods of the Dequeue<T> interface.