peek( ) method of Queue Interface in Java.

peek( ) method of Queue Interface in Java.


Posted in : Core Java Posted on : January 31, 2011 at 5:58 PM Comments : [ 0 ]

In this section we will discuss how can peek( ) method be implemented in Queue interface in java.

peek( ) method of Queue Interface in Java.

In this section we will discuss how can peek( ) method be implemented in Queue interface in java.

Syntax

E peek( )

This method returns the head element of the queue.

In this method you can retrieve the element at the head of the queue. This method returns the element, but does not remove from the head position of the underlying queue. 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. 

Parameter description 

This method does not take any argument but, it returns the element at the head of the queue.

Example of peek( ) method 

In this example we will show you, how does peek( ) method work in Queue interface. This Example will help you to understand  how can you find element at the top position of the queue. Through this example we will show how can you be retrieve the element at the head position of the underlying Queue, and count the total number of elements in queue. 

Example :

package devmanuals.com;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Iterator;
public class QueuePeek {
  public static void main(String args[]) {
    Queue<String> q = new LinkedList<String>();
    q.add("A");
    q.add("B");
    q.add("C");
    q.add("D");
    q.add("E");
    System.out.println("Is Queue empty : " + q.isEmpty());
    System.out.println("Elements of queue = " + q);
    System.out.println("Size of Queue : " + q.size());
    Object obj = q.peek();
    System.out.println("Element at head position = " + obj);
    Iterator iq = q.iterator();
    while (iq.hasNext()) {
      q.remove();
    }
    System.out.println("Is Queue empty : "+q.isEmpty());
    // Here the implementation of peek() method will display null
    System.out.println(q.peek());
  }
}

Output :

Is Queue empty : false

Elements of queue = [A, B, C, D, E]

Size of Queue : 5

Element at head position = A

Is Queue empty : true

null

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics