nobillygreen
nobillygreen

Reputation: 1588

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?

Upvotes: 2

Views: 491

Answers (4)

Andrew Campbell
Andrew Campbell

Reputation: 18645

Comparable defines the natural ordering of a class within a collection while a Comparator allows you to provide a different ordering. If you decide to provide the different Comparator it will override the natural order. By not entering a comparator, it will revert to the natural order set by the compareTo method.

Upvotes: 0

austin
austin

Reputation: 5866

I'm reading through the source code for Oracle's implementation of the PriorityQueue class and it checks if a Comparator is being used and uses that first. Otherwise, it uses the Comparable objects.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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.

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

For a standard PriorityQueue, if you construct it with the Comparator<T>, then that will determine the priority. If not, then the Comparable<T> will determine it. This is all well described in the PriorityQueue API

Upvotes: 3

Related Questions