Java学习 Java 的 Comparable 接口 和 Comparator 接口

写这一篇博客,主要是为了学习Java的元素排序。为了进行元素排序,首先需要定义排序方式。Java的Comparable接口就类似C++中的重载<=,而Java的Comparator接口就类似C++中为sort而定义的comp函数。

接口名称 主要函数
Comparable java.lang int compareTo(T o)(比较此对象与指定对象的顺序)
Comparator java.util int compare(T o1,T o2)(比较用来排序的两个参数) ,boolean equals(Object obj)(指示某个其他对象是否“等于”此Comparator)

一、Comparable 接口

Comparable接口又称为内部比较器
接口定义

Interface Comparable<T> // 'T' - the type of objects that this object may be compared to

接口抽象方法:

int	compareTo(T o); 
// Parameters:
// o - the object to be compared.
// Returns:
// a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than // the specified object.

在一个类中定义Comparable接口,实际上是定义了这个类的自然顺序(natural ordering)。对一个定义了自然顺序的类进行排序,如果不再指定别的排序方式,那么默认按照自然顺序从小到大进行排序。

定义自然顺序的方法如下:

例如我们想要将Person类按照年龄从小到大排序

首先,让Person继承Comparable接口,使之具有“可比”的功能

class Person implements Comparable<Person>

然后,在类内部实现接口的compareTo方法

@Override
public int compareTo(Person arg0) {
	return this.age - arg0.age;
}

完整代码

class Person implements Comparable<Person>{
	private String name;
	private int age;
	
	public Person() {};
	public Person(String name,int age) {
		this.name = name;
		this.age  = age;
	}
	
    public int getAge(){
        return age;
    }
	@Override
	public int compareTo(Person arg0) {
		return this.age - arg0.age;
	}	
}

例如我们已经将若干个Person存储到Collectoins中,对其排序

ArrayList<Person> arrlist = new ArrayList<Person>();
// add data
Collections.sort(arrlist);
// or 
arrlist.sort(null);
  • 前者的排序方法:

调用Collections工具类中的静态方法sort

静态方法的定义

public static <T extends Comparable<? super T>> void sort(List<T> list)

功能介绍

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

  • 后者的排序方法:

调用ArrayList类的成员方法sort,这个sort实际上是ArrayList类实现接口List中定义的抽象方法 sort()

成员方法定义

default void sort(Comparator<? super E> c)

功能介绍

Sorts this list according to the order induced by the specified Comparator.

All elements in this list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements' natural ordering should be used.

This list must be modifiable, but need not be resizable.

同时还给出了参数c的介绍

Parameters:

c - the Comparator used to compare list elements. A null value indicates that the elements' natural ordering should be used

二、Comparator 接口

Comparator接口又称为外部比较器
官方文档

使用Comparator接口的方法

  • step1: 新建一个类,继承自Comparator接口,在内部实现compare函数
class PersonComparator implements Comparator<Person>{
    @Override
    public int compare(Person a,Person b){
        return a.getAge() - b.getAge();
    }
}
  • step2: 用Collections.sort()或List.sort()进行排序
ArrayList<Person> arrlist = new ArrayList<Person>();
// add data
Collections.sort(arrlist,new PersonComparator());
// or
arrlist.sort(new PersonComparator());

使用lambda表达式实现Comparator接口

lambda表达式是一种语法糖,由于Comparator往往语法简单,代码逻辑较少,因此十分适合使用lambda表达式简化。

arrlist.sort((o1,o2)->(o1.getAge()-o2.getAge()));