E peek( ) This method returns an element at the head of the deque.
peek() method of Deque Interface in Java.
In this section we will discuss how can peek() method be implemented in Deque interface.
Syntax
E peek( )
This method returns an element at the head of the deque.
In this method you can find the element at the head of the deque. This method returns the element, but does not remove it from the head position of the underlying deque. The element( ) method is different from this method only by their behavior, peek( ) method returns 'null' if the queue is empty whereas element( ) method throws 'NoSuchElementException' exception. This method is equivalent to the peekFirst() method.
Parameter description
This method does not take any argument but, it returns the element at the head of the deque.
Example of peek( ) method
In this example we will show you, how does peek( ) method work in Deque interface. Through this example we will show how you can retrieve the element at the head position of the underlying deque, and count the total number of elements in deque.
Example :
package devmanuals.com; import java.util.Deque; import java.util.LinkedList; import java.util.Iterator; public class DequePeek { public static void main(String args[]) { Deque<String> dq = new LinkedList<String>(); dq.add("D"); dq.add("E"); dq.add("V"); dq.add("Manuals"); System.out.println("Is Deque empty : " + dq.isEmpty()); System.out.println("Elements of deque = " + dq); System.out.println("Size of deque : " + dq.size()); Object obj = dq.peek(); System.out.println("Element at head position = " + obj); Iterator iq = dq.iterator(); while (iq.hasNext()) { dq.remove(); } System.out.println("Is Deque empty : " + dq.isEmpty()); // Here the implementation of peek() method will display null System.out.println("Therefore returns " + dq.peek()); } }
Output :
Is Deque empty : false Elements of deque = [D, E, V, Manuals] Size of deque : 4 Element at head position = D Is Deque empty : true Therefore returns null |
[ 0 ] Comments