Wednesday, May 16, 2012

Priority Queue Simple Example


The PriorityQueue class implements the Queue interface. When items are added to a PriorityQueue they are not order by First In, First Out . Instead, all items in a PriorityQueue must be comparable (either by implement theComparable interface or by according to a Comparator) which is used to sort the items in the list.

How to declare and initialize a PriorityQueue



The example below shows you how to create a PriorityQueue of Strings. Since String implements Comparable, the Strings will be sorted by the compareTo() methods of the Strings in the Queue. A quick refresh on how compareTo() works for Strings: System.out.println("a".compareTo("ab")); prints out -1.
Note: The PriorityQueue adds and removes based on Comparable; however, if you iterate of the PriorityQueue you may not get the results that you expect. The iterator does not necessarilly go through the elements in the order of their Priority. In other words, if you want to see how the elements are added and removed, do not rely on an iterator. Use the remove() method of the priorityQueue class as is shown in the example code below. Priority Queue Demo
import java.util.*;

public class PriorityQueueDemo {

PriorityQueue<String> stringQueue;


public static void main(String[] args){

stringQueue = new PriorityQueue<String>();
  
stringQueue.add("ab");
stringQueue.add("abcd");
stringQueue.add("abc");
stringQueue.add("a");
 
//don't use iterator which may or may not 
//show the PriorityQueue's order
while(stringQueue.size() > 0)
       System.out.println(stringQueue.remove());
    
}

}
 




Output
a
ab
abc
abcd 

No comments:

Post a Comment