AdSense

AdSense3

Friday 4 September 2015

Java Queue Interface

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

Methods of Queue Interface :

  1. public boolean add(object);
  2. public boolean offer(object);
  3. public remove();
  4. public poll();
  5. public element();
  6. public peek();

PriorityQueue class:

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

Example of PriorityQueue:

  1. import java.util.*;  
  2. class TestCollection12{  
  3. public static void main(String args[]){  
  4.   
  5. PriorityQueue<String> queue=new PriorityQueue<String>();  
  6. queue.add("Amit");  
  7. queue.add("Vijay");  
  8. queue.add("Karan");  
  9. queue.add("Jai");  
  10. queue.add("Rahul");  
  11.   
  12. System.out.println("head:"+queue.element());  
  13. System.out.println("head:"+queue.peek());  
  14.   
  15. System.out.println("iterating the queue elements:");  
  16. Iterator itr=queue.iterator();  
  17. while(itr.hasNext()){  
  18. System.out.println(itr.next());  
  19. }  
  20.   
  21. queue.remove();  
  22. queue.poll();  
  23.   
  24. System.out.println("after removing two elements:");  
  25. Iterator<String> itr2=queue.iterator();  
  26. while(itr2.hasNext()){  
  27. System.out.println(itr2.next());  
  28. }  
  29.   
  30. }  
  31. }  

Output:head:Amit
       head:Amit
       iterating the queue elements:
       Amit
       Jai
       Karan
       Vijay
       Rahul
       after removing two elements:
       Karan
       Rahul
       Vijay

No comments:

Post a Comment