简体   繁体   中英

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?

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM