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
peek()is inherited from theQueueinterface, which only has access to the head of the queue.Dequeis double-ended, so it introduced apeekLast()method andpeekFirst()for symmetry. The docs make it clear that they're equivalent:See also the table at the top: