Benjamin Confino
Benjamin Confino

Reputation: 2364

In Java what should I use for a PriorityQueue that returns the greatest element first?

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.

Upvotes: 2

Views: 2342

Answers (7)

james
james

Reputation: 1377

To add to the Comparator comments, check out:

Collections.reverseOrder();

Upvotes: 1

Hank Gay
Hank Gay

Reputation: 71949

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

Upvotes: 10

neesh
neesh

Reputation: 5265

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.

Upvotes: 0

Jan Jungnickel
Jan Jungnickel

Reputation: 2114

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.

Upvotes: 3

Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35679

From the javadocs:

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

Upvotes: 2

bruno conde
bruno conde

Reputation: 48265

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

Upvotes: 2

Adam Jaskiewicz
Adam Jaskiewicz

Reputation: 10996

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

Upvotes: 2

Related Questions