0

u1Node is some simple container class:

node1 = new u1Node(); 
node2 = new u1Node(); 
node3 = new u1Node(); 
node4 = new u1Node(); 

PriorityQueue<u1Node> minHeap=new PriorityQueue<u1Node>();

Now i'd like to do this:

minHeap.add(node2,43);
minHeap.add(node1,22);
minHeap.add(node4,153);
minHeap.add(node3,2);

In order to do this:

mostImportantObject = new u1Node();
mostImportantObject = minHeap.poll();

And get mostImportantObject=node3, since the "key" to node3 is 2, and it is the lowest key by which the minheap is sorted. It is not permitted to write in this way in java, so how should i do it?

user3573388
  • 191
  • 1
  • 6
  • `The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time` – njzk2 Oct 03 '14 at 15:01

1 Answers1

0

You need to provide the appropriate Comparator<u1Node> when you initialize the queue:

minHeap = new PriorityQueue<u1Node>(10, new Comparator<u1Node>() {
  @Override int compare(u1Node o1, u1Node o2) {
    // return -1, 0, 1 depending whether o1 has priority
    // less, equals or bigger than o2.
    ..... // your code here
  }
});

That is if you u1Node does not implement Comparable<u1Node>. If it does, the queue will use the natural order.

Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94