here is one code:
import java.util.*;
class PQ
{
static class PQsort
implements Comparator<Integer> {
public int compare(Integer one, Integer two) {
return two - one; // unboxing
}
}
public static void main(
String[] args)
{
int[] ia = {1,5,3,7,6,9,8 }; // unordered data
PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>(); // use natural order
for(int x : ia) // load queue
pq1.offer(x);
for(int x : ia)
System.out.print(pq1.poll() + " ");
System.out.println("");
PQsort pqs = new PQsort(); // get a Comparator
PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10,pqs); // use Comparator
for(int x : ia) // load queue
pq2.offer(x);
System.out.println("size " + pq2.size());
System.out.println("peek " + pq2.peek());
System.out.println("size " + pq2.size());
System.out.println("poll " + pq2.poll());
System.out.println("size " + pq2.size());
for(int x : ia) // review queue
System.out.print(pq2.poll() + " ");
}
}
in this code i dint understand that how the comparator is working.How does it arrange the elements in the queue?
espicially this one:
[b]implements Comparator<Integer> {
public int compare(Integer one, Integer two) {
return two - one; // unboxing
}
how does this works?please explain!