Java比较器-Comparable和Comparator

本文深入探讨了Java中Comparable与Comparator接口的功能与应用,详细解析了它们如何帮助对象进行排序,并提供了具体的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Comparable

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

接口定义:

public interface Comparable<T> {
    public int compareTo(T o);
}

  Comparable接口位于java.lang包下,Comparable相当于内部比较器。实现该接口的类为支持排序的,实现该接口的对象的List(或Array)可通过Collection.sort(或Arrays.sort)排序。此外,实现该接口的对象可以作为sorted map的键或sorted set中的元。使用范例如下:

public class Cat implements Comparable{

    private int age;

    private String name;

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

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

    // 不指定Comparable范型类型时,比较对象为Object
    @Override
    public int compareTo(Object o) {
        return this.age - ((Cat)o).age;
    }

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

    public static void main(String[] args) {
        Cat cat1 = new Cat(1, "XXXX");
        Cat cat2 = new Cat(3, "YYYY");
        Cat cat3 = new Cat(2, "ZZZZ");

        List<Cat> cats = new ArrayList<Cat>();
        cats.add(cat1);
        cats.add(cat2);
        cats.add(cat3);

        Collections.sort(cats);

        for(Cat cat : cats) {
            System.out.println(cat);
        }
    }

}

  类Cat不实现Comparable接口时,Collection.sort方法不可用,会提示Cat类实现该接口。实现Comparable接口时可以指定范型类型,也可以不指定,指定具体范型类型时compareTo方法的参数为范型类型,不指定时默认为Object。

Comparator

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

接口定义:

public interface Comparator<T> {

    int compare(T o1, T o2);
    boolean equals(Object obj);

    ...
}

  Comparator接口位于java.util包下,Comparator相当于外部比较器。一个类除了实现Comparable方法,让自己具有排序功能外,也可以通过外部定义比较器Comparator,传递给Collections.sort(或 Arrays.sort)等方法实现排序。同样,实现Comparator接口可不指定具体范型类型,这时默认比较类行为Object。说明:实现Comparator接口的对象必须实现compare方法,但可以不实现equals方法,因为Object类中默认实现了equals方法。

使用范例:

public class Cat {

    private int age;

    private String name;

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

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

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

    public static void main(String[] args) {
        Cat cat1 = new Cat(1, "XXXX");
        Cat cat2 = new Cat(3, "YYYY");
        Cat cat3 = new Cat(2, "ZZZZ");

        List<Cat> cats = new ArrayList<Cat>();
        cats.add(cat1);
        cats.add(cat2);
        cats.add(cat3);

         // 也可单独定义实现Comparator接口的比较类
        Collections.sort(cats, new Comparator<Cat>() {
            @Override
            public int compare(Cat o1, Cat o2) {
                return o1.age - o2.age;  // 降序:return o2.age - o1.age;
            }
        });

        for(Cat cat : cats) {
            System.out.println(cat);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值