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

此生再无相见时 提交于 2019-12-06 07:29:41

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!