You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PriorityQueue构造器是否返回多个Comparator?为何仅返回一个实例

Understanding the Composite Comparator in Your PriorityQueue Code

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 basic Comparator that sorts students by their CGPA in ascending order.
  • .reversed(): Returns a new Comparator that reverses the order of the previous one (so now we sort CGPA in descending order).
  • .thenComparing(Student::getFname): Returns a new composite Comparator — 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 composite Comparator — 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:

  1. First compare CGPA (highest value first)
  2. If tied, compare first names (alphabetical order)
  3. If still tied, compare tokens (smallest numeric value first)

内容的提问来源于stack exchange,提问作者koogtt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:57:40