0

I have a comparator class NComparator that compares 2 Node objects and returns either 1, -1, or 0.

I initialized a PriorityQueue with an initial capacity of 100 and that NComparator.

    NComparator nc = new NComparator();
    PriorityQueue<Node> pq = new PriorityQueue<Node>(100, nc);

I have about 25 Node objects (that can be compared with NComparator), and I added them all to the PriorityQueue Object:

  pq.add(new Node("A", 3));
  pq.add(new Node("G", 1));
  pq.add(new Node("B", 10));
  .... etc

How can I arrange these node objects in PriorityQueue by the priority returned by the comparator (which only compares pairwise combinations of nodes)? Specifically, I would like to be able to access the two nodes with the least priority in this PriorityQueue. How can I do that?

2 Answers2

2

The PriorityQueue API only supports getting the single node with the least priority, but you could remove that and then query again to get the next lowest element.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Thanks, I see. I did not also realize that when I do pq.add, PriorityQueue automatically adds them so they are always retained in order. So removing on element will be removing its lowest priority. –  Jul 09 '13 at 22:24
0

If are you sure that your NComparator arranges the Node elements correctly, and the least priorities are at the head of the queue, then you only need to do, twice: pq.poll() See the PriorityQueue API

Example:

  Node firstLowerNode = pq.poll();
  Node secondLowerNode = pq.poll();
Jesfre
  • 702
  • 8
  • 13