Sunday, 6 April 2014

peek : Retrieves the head of this queue

E peek() return the head of this queue, or null if this queue is empty

import java.util.*;
class QueuePeek{
 public static void main(String args[]){
  Queue<Integer> myQueue1 = new PriorityQueue<> ();
  Queue<Integer> myQueue2 = new PriorityQueue<> ();
  
  /* Add Elements to myQueue */
  myQueue1.add(10);
  myQueue1.add(20);
  myQueue1.add(30);
  myQueue1.add(40);
  myQueue1.add(50);
  
  /* Make the myQueue2 null */
    
  System.out.println("\nElements in myQueue1 are");
  System.out.println(myQueue1);
  System.out.println("Head Element " + myQueue1.peek() + " Retrieved from the Queue ");
  
  System.out.println("\nElements in myQueue2 are");
  System.out.println(myQueue2);
  System.out.println("Head Element " + myQueue2.peek() + " removed from the Queue ");
  
 }
}

Output
Elements in myQueue1 are
[10, 20, 30, 40, 50]
Head Element 10 Retrieved from the Queue

Elements in myQueue2 are
[]
Head Element null removed from the Queue

1. throws NullPointerException if this queue is null
import java.util.*;

class QueuePeekNull{
 public static void main(String args[]){
  Queue<Integer> myQueue = new PriorityQueue<> ();
  
  myQueue = null;
  
  myQueue.peek();
 }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at QueuePeekNull.main(QueuePeekNull.java:9)





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment