Reputation: 33
I read the documentation about Deque, it just say the peek method will return head of the queue represented by this Deque. But how it know my structure is queue or stack.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
/**
* Created by fang on 7/30/17.
*/
public class DequeMethods {
public static void main(String[] args){
Deque<Integer> queue = new LinkedList<>();
Deque<Integer> stack = new LinkedList<>();
for(int i=0;i<100;i++){
queue.offer(i);
stack.push(i);
}
System.out.println(queue.peek());
System.out.println(stack.peek());
}
}
Upvotes: 0
Views: 971
Reputation: 853
It does not know if it's queue or stack, as you already mentioned peek will just return head of the Deque. Main point here is what is head value on push & offer (also pull & poll), incase of push head will be pointing to newly pushed element but in offer head will still be pointing to first inserted element. So peek just returns head value and head value is updated by the queue/stack methods called.
For more clarity checkout point 4.1 & 4.2 here https://www.baeldung.com/java-array-deque.
Upvotes: 1