0Pricing
Java Academy · 课时

Comparable 接口

实现 Comparable,为类提供自然排序,并将其与 Collections.sort 结合使用

Comparable 接口 是 CoddyKit 上的免费 Java Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Java Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Java Academy 课程共包含 4 节课。

可比较接口

Comparable<T> 为类定义自然顺序。实现它后,实例即可使用 Collections.sort()、Arrays.sort() 以及 TreeSet 等排序集合进行排序。

实现可比较接口

实现 compareTo(T other),并返回负数(当前对象小于参数对象)、零(相等)或正数(当前对象大于参数对象)。

class Product implements Comparable<Product> {
    private final String name;
    private final double price;

    Product(String name, double price) {
        this.name = name; this.price = price;
    }

    @Override
    public int compareTo(Product other) {
        return Double.compare(this.price, other.price); // ascending by price
    }

    @Override public String toString() { return name + "($" + price + ")"; }
}

List<Product> products = new ArrayList<>(List.of(
    new Product("Mouse", 29.99),
    new Product("Laptop", 999.0),
    new Product("Keyboard", 79.99)
));
Collections.sort(products);
System.out.println(products); // [Mouse($29.99), Keyboard($79.99), Laptop($999.0)]

compareTo 契约

正确实现可比较接口需要满足以下契约:

  • 反对称性:符号函数(a.compareTo(b)) == -符号函数(b.compareTo(a))
  • 传递性:如果 a > b 且 b > c,则 a > c
  • 一致性:a.compareTo(b) == 0 意味着 a.equals(b),强烈建议满足这一点

安全比较基本类型

不要在 compareTo 中直接用基本类型相减,因为整数溢出可能导致错误结果。请使用 Integer.compare()、Double.compare() 等方法。

// WRONG: integer subtraction can overflow
int compareTo(Player other) {
    return this.score - other.score; // overflow if scores differ by > Integer.MAX_VALUE
}

// CORRECT: use Integer.compare
int compareTo(Player other) {
    return Integer.compare(this.score, other.score);
}

// For strings: delegate to String.compareTo
int compareTo(Player other) {
    return this.name.compareTo(other.name); // String handles it correctly
}

TreeSet 中的自然顺序

实现可比较接口的类会自动按照顺序放入 TreeSet 和 TreeMap 等排序集合中。

class Priority implements Comparable<Priority> {
    enum Level { LOW, MEDIUM, HIGH, CRITICAL }
    final Level level;
    final String task;
    Priority(Level level, String task) { this.level = level; this.task = task; }
    @Override
    public int compareTo(Priority other) {
        return this.level.compareTo(other.level); // enum ordinal order
    }
    @Override public String toString() { return level + ": " + task; }
}

TreeSet<Priority> queue = new TreeSet<>();
queue.add(new Priority(Priority.Level.CRITICAL, "Fix prod crash"));
queue.add(new Priority(Priority.Level.LOW, "Update docs"));
queue.add(new Priority(Priority.Level.HIGH, "Deploy feature"));
queue.forEach(System.out::println);
// LOW: Update docs
// HIGH: Deploy feature
// CRITICAL: Fix prod crash

多字段可比较接口

要根据多个字段排序,请链接多个比较:先比较主要字段;如果主要字段相等,再比较次要字段。

class Employee implements Comparable<Employee> {
    final String dept, name;
    final double salary;

    Employee(String dept, String name, double salary) {
        this.dept = dept; this.name = name; this.salary = salary;
    }

    @Override
    public int compareTo(Employee other) {
        int deptCmp = this.dept.compareTo(other.dept);
        if (deptCmp != 0) return deptCmp;           // primary: by dept
        return this.name.compareTo(other.name);      // secondary: by name
    }
}

可比较接口与 equals 的一致性

强烈建议(但并非必需)满足 a.compareTo(b) == 0 当且仅当 a.equals(b)。违反这一点会在排序集合和映射中造成隐蔽错误。

// BigDecimal violates this: new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) == 0
// but new BigDecimal("2.0").equals(new BigDecimal("2.00")) == false

// This causes TreeSet to treat them as equal (only one stored)
TreeSet<java.math.BigDecimal> set = new TreeSet<>();
set.add(new java.math.BigDecimal("2.0"));
set.add(new java.math.BigDecimal("2.00"));
System.out.println(set.size()); // 1 — compareTo-equal → same element

使用 Collections.sort 排序

Collections.sort() 和 Arrays.sort() 使用由可比较接口定义的自然顺序。

List<String> names = new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
Collections.sort(names); // natural alphabetical order
System.out.println(names); // [Alice, Bob, Charlie]

String[] arr = {"banana", "apple", "cherry"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [apple, banana, cherry]

// Stream sorted() uses natural order
names.stream().sorted().forEach(System.out::println);

二分查找中的可比较接口

Collections.binarySearch() 要求列表已按自然顺序排序,并且元素实现可比较接口。

List<Integer> sorted = new ArrayList<>(List.of(1, 3, 5, 7, 9, 11));
int idx = Collections.binarySearch(sorted, 7);
System.out.println("Found 7 at index: " + idx); // 3

int missing = Collections.binarySearch(sorted, 4);
System.out.println("4 not found, insertion point: " + (-missing - 1)); // 2

可比较接口与 Comparator 对比

主要区别:

  • 可比较接口:定义类自身的自然顺序——每个类只有一个
  • Comparator:定义外部排序顺序——数量不限,并且可以组合

实践:排行榜

使用可比较接口实现按分数降序排列的自然顺序排行榜。

class LeaderboardEntry implements Comparable<LeaderboardEntry> {
    final String player;
    final int score;
    final long timestamp;

    LeaderboardEntry(String player, int score) {
        this.player = player; this.score = score;
        this.timestamp = System.nanoTime();
    }

    @Override
    public int compareTo(LeaderboardEntry other) {
        int scoreCmp = Integer.compare(other.score, this.score); // descending
        if (scoreCmp != 0) return scoreCmp;
        return Long.compare(this.timestamp, other.timestamp); // earlier = higher
    }

    @Override public String toString() { return player + ": " + score; }
}

TreeSet<LeaderboardEntry> board = new TreeSet<>();
board.add(new LeaderboardEntry("Alice", 950));
board.add(new LeaderboardEntry("Bob", 1200));
board.add(new LeaderboardEntry("Carol", 950));
board.forEach(System.out::println);
// Bob: 1200 / Alice: 950 / Carol: 950

快速检查

当当前对象小于参数时,compareTo() 返回什么?

回顾:可比较接口

要点:

  • 实现可比较接口以定义类的自然顺序
  • compareTo 返回负数(较小)、零(相等)或正数(较大)
  • 使用 Integer.compare()/Double.compare(),不要直接相减(存在溢出风险)
  • 多字段排序时链接比较:主要字段 → 次要字段
  • 自然顺序由 Collections.sort、Arrays.sort、TreeSet 和 TreeMap 使用
  • 可比较接口只定义 ONE 个顺序;需要多种顺序时请使用 Comparator

常见问题解答

「Comparable 接口」课时是免费的吗?

是的 — 「Comparable 接口」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Java Academy 课程的其余内容,请升级到 CoddyKit PRO。 Java Academy 课程共包含 4 节课。

「Comparable 接口」这节课中我会学到什么?

实现 Comparable,为类提供自然排序,并将其与 Collections.sort 结合使用 你通过在浏览器中直接运行的动手代码来练习 Java Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Java Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Java Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「Comparable 接口」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Java Academy 课中编写并运行代码吗?

能。每节 Java Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Comparable 接口
  2. Comparator 与 Lambda 排序
  3. 使用 thenComparing 进行多关键字排序
  4. 实际应用中的数组与集合排序
← 返回 Java Academy