Comparator接口(自然排序)
为什么需要Comparator接口
当不想使用在类中Comparabel接口实现的comparaTo()方法,需要特殊的排序方法时,一般使用该接口
public class ComparableTest {
public static void main(String[] args) {
Person[] people = new Person[4];
people[0] = new Person(20,"zhangsan");
people[1] = new Person(22,"lisi");
people[2] = new Person(10,"wangwu");
people[3] = new Person(25,"zhaoliu");
Arrays.sort(people);
System.out.println("Comparable接口"+Arrays.toString(people));
//不想使用按年龄排序的方式了,想要使用按名字字母从大到小排序的方式
Arrays.sort(people, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return - o1.getName().compareTo(o2.getName());
}
});
System.out.println("Comparator接口"+Arrays.toString(people));
}
}
class Person implements Comparable{
private int age;
private String 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;
}
public Person() {
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
//Comparable接口中 想要按年龄进行从小到大排序
@Override
public int compareTo(Object o) {
if (o instanceof Person){
Person person = (Person)o;
if (this.age > person.age){
//this年龄大于形参的年龄 返回正整数
return 1;
}else if (this.age < person.age){
//this年龄小于形参的年龄 返回负整数
return -1;
}else {
return 0;
}
}
throw new ClassCastException("比较对象有误");
}
}
比较:
Comparable接口和Comparator都是排序的接口
但是Comparable接口实现的方法写在类中,一劳永逸,适用于一种排序方法使用多次的情况;
Comparator接口一般直接用匿名的方式卸载Arrays.sort()方法的参数中,一般适用于使用次数不多,想要进行特殊的排序方式的情况