user1830307
user1830307

Reputation:

PriorityQueue, what am I missing?

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?

Upvotes: 0

Views: 142

Answers (2)

Jesfre
Jesfre

Reputation: 702

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();

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198471

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.

Upvotes: 2

Related Questions