Comparable和Comparator接口都是实现集合中元素的比较、排序的,众所周知,诸如Integer,double等基本数据类型,java可以对他们进行比较,而对于类的比较,需要人工定义比较用到的字段比较逻辑。总体来讲,可以把Comparable理解为内部比较器,而Comparator是外部比较器。Comparable需要修改源码,Comparator则不需要!
1、Comparable(内部比较器)
- 实现了Comparable接口的类中需要重写 int compareTo(T o)方法。
- 实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays.sort进行自动排序。
public class Person implements Comparable<Person> {
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
@Override
public int compareTo(Person o) {
return this.age - o.age; //从小到大排序!
}
}
编写测试类,来对person对象进行排序:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Person p1 = new Person("zhangsan", 20);
Person p2 = new Person("lisi", 18);
Person p3 = new Person("wangwu", 25);
Person[] persons = {p1, p2, p3};
System.out.println("排序前");
for (Person person : persons) {
System.out.println(person.name + ":" + person.age);
}
//Arrays是数组工具类,Collections是集合工具类
Arrays.sort(persons);
System.out.println("排序后");
for (Person person : persons) {
System.out.println(person.name + ":" + person.age);
}
}
}
2、Comparator(外部比较器)
- 不改变源码,从新创建一个类,该类实现了Comparator的接口
- 重写 int compare(T o1, T o2)方法 是“比较o1和o2的大小”。
创建Person类:
public class Person {
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
}
来创建person类的比较器PersonComparator类:
import java.util.Comparator;
public class PersonComparator implements Comparator<Person>{
@Override
public int compare(Person o1, Person o2) {
return o1.age - o2.age;
}
}
编写测试类:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Person p1 = new Person("zhangsan", 20);
Person p2 = new Person("lisi", 18);
Person p3 = new Person("wangwu", 25);
Person[] persons = {p1, p2, p3};
System.out.println("排序前");
for (Person person : persons) {
System.out.println(person.name + ":" + person.age);
}
Arrays.sort(persons, new PersonComparator());
System.out.println("排序后");
for (Person person : persons) {
System.out.println(person.name + ":" + person.age);
}
}
}