Search code examples
javalinked-listdequepeek

What is the difference between a LinkList's peek vs peekFirst?


I've read through the docs and looked through the java source code. I don't understand the difference between the following:

  • java.util.Deque - peek() Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.

vs

  • java.util.Deque - peekFirst() Retrieves, but does not remove, the first element of this deque, or returns null if this deque is empty.

No matter what I do, I cannot get a different result when calling these 2 methods. Do they always return the same? Is one just for backwards compatibility?

https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html

import java.util.LinkedList;
public class MyClass {
    public static void main(String args[]) {
        LinkedList<Integer> l = new LinkedList<>();
            l.add(2);
            l.addFirst(3);
            l.add(4);
            l.addLast(5);
            l.remove(2);
            l.offer(6);
            l.poll();
            l.add(7);
        System.out.println(l.toString());
        System.out.println(l.peek());
        System.out.println(l.peekFirst());
    }
}

Returns the following:

[2, 5, 6, 7] // toString

2 // peek

2 // peekFirst


Solution

  • peek() is inherited from the Queue interface, which only has access to the head of the queue. Deque is double-ended, so it introduced a peekLast() method and peekFirst() for symmetry. The docs make it clear that they're equivalent:

    This method is equivalent to peekFirst().

    See also the table at the top:

    The methods inherited from the Queue interface are precisely equivalent to Deque methods as indicated in the following table:

        Comparison of Queue and Deque methods
    +────────────────+───────────────────────────+
    |  Queue Method  |  Equivalent Deque Method  |
    +────────────────+───────────────────────────+
    | add(e)         | addLast(e)                |
    | offer(e)       | offerLast(e)              |
    | remove()       | removeFirst()             |
    | poll()         | pollFirst()               |
    | element()      | getFirst()                |
    | peek()         | peekFirst()               |
    +────────────────+───────────────────────────+