Comparable 和 Comparator

TreeSet与TreeMap排序
本文介绍了如何使用Java中的TreeSet和TreeMap进行排序。TreeSet对象和TreeMap的Key必须实现Comparable接口或Comparator接口。文章通过具体示例展示了如何为自定义类Student实现Comparable接口以实现基于年龄的排序,并提供了使用Comparator接口进行排序的例子。

TreeSet 和 TreeMap 排序 TreeSet对象和 TreeMap的Key必须实现Comparable 接口或Comparator接口

1、Comparable

引用Comparable 接口 必须实现其compareTo方法

public class Student implements Serializable,Comparable<Student>{
    public String name;
    public int age;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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


    @Override
    public int compareTo(Student o) {
        if(null == o)  return -1;
        return this.getAge() - o.getAge();
    }

2、Comparator

只拿TreeSet举例了

//
 TreeSet<Student> treeSet = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Student s1 = (Student) o1;
                Student s2 = (Student) o2;

                if (s1.getAge() > s2.getAge()) return 1;
                if(s1.getAge() < s2.getAge()) return -1;
                if(s2.getAge() == s1.getAge()) return s1.getName().compareTo(s2.getName());
                return 1;
            }
        });
`Comparable` `Comparator` 都是用来对对象排序的接口,但在使用场景设计意图上有所不同。 ### 1. **Comparable 接口** `Comparable<T>` 是 Java 中的一个泛型接口,它允许你在定义类的时候指定该类的对象应该如何比较大小。通常用于表示自然顺序(natural ordering),例如数字从小到大、字符串按字典序等。 #### 特点: - 类本身需要实现这个接口,并提供 `compareTo(T o)` 方法的具体实现。 - 只能有一种比较规则,即只能有一个“自然”排序方式。 - 如果某个类实现了 `Comparable`,那么它的实例可以直接通过 `Collections.sort()` 或 `Arrays.sort()` 进行排序。 **示例:** ```java public class Person implements Comparable<Person> { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public int compareTo(Person other) { return Integer.compare(this.age, other.age); // 按年龄升序排列 } } ``` --- ### 2. **Comparator 接口** `Comparator<T>` 同样是一个泛型接口,但它不是由类直接实现的,而是作为外部策略模式来使用的。你可以创建一个独立的 Comparator 实现类或匿名内部类,甚至可以使用 lambda 表达式,在运行时动态地传递给排序算法。 #### 特点: - 提供了更灵活的比较逻辑,可以在不修改原有类的情况下为同一个类提供多种排序方式。 - 可以有多个不同的 `Comparator` 来处理同一种类型的对象的不同排序需求。 - 经常与 `TreeSet`, `PriorityQueue` 等数据结构一起使用,也可以传入 `sort()` 方法中作为参数。 **示例:** ```java import java.util.*; List<Person> people = new ArrayList<>(); // 添加一些Person对象... // 使用Comparator按名字排序 people.sort(Comparator.comparing(person -> person.getName())); // 或者按年龄降序排序 people.sort((p1, p2) -> Integer.compare(p2.getAge(), p1.getAge())); ``` --- ### 总结 - **Comparable**:适合于对象自带的一种天然有序关系,且这种顺序通常是唯一的; - **Comparator**:适用于当你想要在同一组对象上有多种不同的排序方式,或者不想改变原始类的设计时; 选择哪一个取决于具体的业务需求以及你希望如何组织代码。 --
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值