In Java, the PriorityQueue class is implemented as a priority heap. Heap is an important data structure in computer science. For a quick overview of heap, here is a very good tutorial.
1. Simple Example
The following examples shows the basic operations of PriorityQueue such as offer(), peek(), poll(), and size().
importjava.util.Comparator;importjava.util.PriorityQueue;publicclass PriorityQueueTest {staticclass PQsort implements Comparator<Integer>{publicint compare(Integer one, Integer two){return two - one;}}publicstaticvoid main(String[] args){int[] ia ={1, 10, 5, 3, 4, 7, 6, 9, 8};
PriorityQueue<Integer> pq1 =new PriorityQueue<Integer>();// use offer() method to add elements to the PriorityQueue pq1for(int x : ia){
pq1.offer(x);}System.out.println("pq1: "+ pq1);
PQsort pqs =new PQsort();
PriorityQueue<Integer> pq2 =new PriorityQueue<Integer>(10, pqs);// In this particular case, we can simply use Collections.reverseOrder()// instead of self-defined comparatorfor(int x : ia){
pq2.offer(x);}System.out.println("pq2: "+ pq2);// print sizeSystem.out.println("size: "+ pq2.size());// return highest priority element in the queue without removing itSystem.out.println("peek: "+ pq2.peek());// print sizeSystem.out.println("size: "+ pq2.size());// return highest priority element and removes it from the queueSystem.out.println("poll: "+ pq2.poll());// print sizeSystem.out.println("size: "+ pq2.size());System.out.print("pq2: "+ pq2);}}