PriorityQueue构造器是否返回多个Comparator?为何仅返回一个实例
Great question! Let's clear up the confusion here: your code does NOT return multiple Comparator instances — it creates a single, composite Comparator that bundles all your sorting rules together. Here's how it works:
How the Chained Calls Build a Single Comparator
Every method in that chain returns a new Comparator instance that combines the previous logic with the new rule:
Comparator.comparing(Student::getCgpa): Starts by creating a basicComparatorthat sorts students by their CGPA in ascending order..reversed(): Returns a newComparatorthat reverses the order of the previous one (so now we sort CGPA in descending order)..thenComparing(Student::getFname): Returns a new compositeComparator— this one first uses the CGPA-descending rule; if two students have the same CGPA, it falls back to sorting by their first name (ascending, the default)..thenComparing(Student::getToken): Adds one more layer to the compositeComparator— if CGPA and first name are identical, it finally sorts by the student's token value (ascending).
Why This Works with PriorityQueue's Constructor
The PriorityQueue constructor only accepts one Comparator instance, but that instance can encapsulate multiple sequential sorting rules. Java's Comparator interface includes these default methods (reversed(), thenComparing(), etc.) specifically to let you build these layered, composite comparison logics without having to write a huge custom Comparator class from scratch.
When the PriorityQueue uses this composite Comparator, it follows the rules in strict order:
- First compare CGPA (highest value first)
- If tied, compare first names (alphabetical order)
- If still tied, compare tokens (smallest numeric value first)
内容的提问来源于stack exchange,提问作者koogtt

