views:

412

answers:

7

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.

+8  A: 

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);
    }
}
Hank Gay
thanks, I'll go teach myself how to do that :)
Benjamin Confino
If you have a Comparator already but you want the reverse sort, you might find Collections.reverseOrder() helpful.
Alex Miller
Thanks, but I just finished writing it, 0 - arg0.compareTo(arg1) is neater than my if, else if one I think I'll use that instead.
Benjamin Confino
+2  A: 

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

Adam Jaskiewicz
+2  A: 

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

bruno conde
+1  A: 

From the javadocs:

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
Rob Stevenson-Leggett
+2  A: 

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.

Jan Jungnickel
A: 

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.

neesh
A: 

To add to the Comparator comments, check out:

Collections.reverseOrder();
james