Question

Java's PriorityQueue places the least element at the head of the list, however I need it to place the greatest element at the head. What what's the neatest way to get a priority queue that behaves like that.

Since I wrote the class stored in this queue I could simply reverse the results of compareTo, its not used outside this queue.

However I like to make the code an accurate representation of what I'm modeling, what I'm trying to do is get the greatest first so the code should say that rather than least first with an unusual definition of least.

[edit]just a quick thank you everyone, Comparator sounds like what I need just as soon as I teach myself how to write one.

Was it helpful?

Solution

Pass a Comparator that inverts the natural order when you instantiate the PriorityQueue.

It would look something like this:

public class ReverseYourObjComparator implements Comparator<YourObj> {
    public int compare(final YourObj arg0, final YourObj arg1) {
        return 0 - arg0.compareTo(arg1);
    }
}

OTHER TIPS

You basically have the solution right in your question: You can pass a Comparator to the constructor of a PriorityQueue. The Comparator will influence the way the items will be ordered.

I'd just use a Comparator. This way the sorting order is used only in your Queue, rather than attached to your class.

Simply provide the PriorityQueue a Custom Comparator<? super E> throgh the constructor and change the order of the elements.

From the javadocs:

PriorityQueue(int initialCapacity, Comparator<? super E> comparator) 

To add to the Comparator comments, check out:

Collections.reverseOrder();

The api documentation on PriorityQueue says: "The head of this queue is the least element with respect to the specified ordering". So the definition of least is subjective based on your specific ordering which is why you have the option of providing a comparator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top