Thursday 7 May 2015

Queue Interface and Class

Java Queue

The Queue interface basically orders the element in FIFO(First In First Out)manner.

public boolean add(object); Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

public boolean offer(object); -Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception.

public remove(); - Retrieves and removes the head of this queue. This method differs from poll only in that it throws an exception if this queue is empty.

public poll();Retrieves and removes the head of this queue, or returns null if this queue is empty.

public element(); - Retrieves and removes the head of this queue, or returns null if this queue is empty.

public peek(); - Retrieves, but does not remove, the head of this queue. This method differs from peek only in that it throws an exception if this queue is empty.

Priority Queue class

The Priority Queue class provides the facility of using queue. 
But it does not orders the elements in FIFO manner.

Example,

PriorityQueue<String> queue=new PriorityQueue<String>();  
queue.add("queue value 1");
queue.add("queue value 2");
queue.add("queue value 3");

System.out.println("head:"+queue.element());  
System.out.println("head:"+queue.peek());  

System.out.println("iterating the queue elements:"); 
Iterator itr=queue.iterator(); 
while(itr.hasNext()){ 
System.out.println(itr.next()); 

queue.remove(); 
queue.poll(); 

 System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator(); 
while(itr2.hasNext()){ 
  System.out.println(itr2.next());  
} 



Output:head:queue value 1
       head:queue value 1
       iterating the queue elements:
       queue value 1
       queue value 2
       queue value 3
       
       after removing two elements:
       queue value 3
      

No comments:

Post a Comment