2025-08-28 15:19

Comparable 和 Comparator接口

王姐姐

Java后端

(118)

(0)

收藏

ComparableComparator 是 Java 中用于对象排序的两个接口,区别如下:


1. Comparable自然排序(对象自己定义规则)

实现该接口的类,自己决定怎么排序。

public class Student implements Comparable<Student> {
    private int age;

    public Student(int age) {
        this.age = age;
    }

    // 按年龄升序排序
    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // 升序
    }

    @Override
    public String toString() {
        return "Student{" + "age=" + age + '}';
    }
}

使用:

List<Student> students = Arrays.asList(new Student(20), new Student(18));
Collections.sort(students); // 自动按年龄排序
System.out.println(students); // [Student{age=18}, Student{age=20}]

适合:一个类有默认排序规则(如年龄、ID)。

2. Comparator外部排序(别人定义规则)

不修改类,外部定义排序方式,更灵活。

// 按年龄降序排序
Comparator<Student> byAgeDesc = (s1, s2) -> s2.age - s1.age;

// 或按字符串长度排序(假设学生有姓名)
Comparator<Student> byNameLength = (s1, s2) -> 
    s1.getName().length() - s2.getName().length();

使用:

students.sort(byAgeDesc);
System.out.println(students); // [Student{age=20}, Student{age=18}]

适合:多种排序规则,或不能修改原类。


总结对比

接口

所在位置

特点

使用场景

Comparable

类内部实现

定义自然顺序(默认排序)

一个类一个默认排序规则

Comparator

外部定义(类外)

定义临时/多种排序规则

灵活排序,不修改原类

 记忆:  

  • Comparable → “我(对象)能被比较”  

  • Comparator → “我(工具)用来比较别人”


0条评论

点击登录参与评论