Sunday, 6 April 2014

element : Retrieves the Head Of the Queue

E element()
Retrieves, but does not remove, the head of this queue.

import java.util.*;
class QueueElement{
 public static void main(String args[]){
  Queue<Integer> myQueue = new PriorityQueue<> ();
  
  /* Add Elements to myQueue */
  myQueue.offer(10);
  myQueue.offer(20);
  myQueue.offer(30);
  myQueue.offer(40);
  
  System.out.println("\nElements in myQueue are");
  System.out.println(myQueue);
  System.out.println("Head Element " + myQueue.element() + " retrieved from the Queue ");
  
  System.out.println("\nElements in myQueue are");
  System.out.println(myQueue);
  System.out.println("Head Element " + myQueue.element() + " retrieved from the Queue ");

 }
}

Output
Elements in myQueue are
[10, 20, 30, 40]
Head Element 10 retrieved from the Queue

Elements in myQueue are
[10, 20, 30, 40]
Head Element 10 retrieved from the Queue

1. throws NoSuchElementException if this queue is empty
import java.util.*;
class QueueElementNoSuch{
 public static void main(String args[]){
  Queue<Integer> myQueue = new PriorityQueue<> ();
    
  System.out.println("\nElements in myQueue are");
  System.out.println(myQueue);
  System.out.println("Head Element " + myQueue.element() + " retrieved from the Queue ");
 }
}

Output
Elements in myQueue are
[]
Exception in thread "main" java.util.NoSuchElementException
        at java.util.AbstractQueue.element(Unknown Source)
        at QueueElementNoSuch.main(QueueElementNoSuch.java:8)
 
2. throws NullPointerException if this queue is null
import java.util.*;
class QueueElementNull{
 public static void main(String args[]){
  Queue<Integer> myQueue = new PriorityQueue<> ();
    
  myQueue = null;
  
  System.out.println("\nElements in myQueue are");
  System.out.println(myQueue);
  System.out.println("Head Element " + myQueue.element() + " retrieved from the Queue ");
 }
}

Output
Elements in myQueue are
null
Exception in thread "main" java.lang.NullPointerException
        at QueueElementNull.main(QueueElementNull.java:10)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment