Search code examples
javapriority-queuecomparatorcompareto

Using a comparator and a separate compareTo method for a PriorityQueue


If I have a PriorityQueue made up of T objects, and T has a compareTo() method and implements comparable, but my PriorityQueue also takes a comparator as a parameter, what is my PriorityQueue going to look to for the ordering of its elements?

In other words, which one determines the priority of the objects? The compareTo() method or the provided comparator?


Solution

  • The documentation for the comparator parameter of the constructor states that

    comparator - the comparator used to order this priority queue. If null then the order depends on the elements' natural ordering.

    This means that when a comparator is specified, the natural ordering established by the compareTo method is ignored.