对象比较器
1、Comparable接口
此接口强行对实现它的每个类的对象进行整体排序,这种排序成为类的自然排序,类的compareTo方法称为类的自然比较方法。
代码示例
import java.util.Arrays;
public class Cat implements Comparable<Cat> {
private String name;
private int age;
public Cat() {}
public Cat(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 "Cat [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Cat o) {
return this.age - o.age;
}
// 添加main方法测试
public static void main(String[] args) {
Cat[] cats = { new Cat("Tom", 2), new Cat("Mikey", 1), new Cat("Jerry", 8) };
Arrays.sort(cats);
System.out.println(Arrays.toString(cats));
}
}
输出结果
2、Comparator接口
Comparable接口要求自定义去实现,按照oo原则,应当对修改关闭,对扩展开放。
如果这个类已经定义好了,不想再去修改它,想实现比较,该如何实现呢?
Comparator接口:强行对某个对象Collection进行整体排序的比较
代码示例
已经写好的Dog类
import java.util.Arrays;
public class Dog {
private String name;
private int age;
public Dog() {}
public Dog(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 "Dog [name=" + name + ", age=" + age + "]";
}
// 添加main方法测试
public static void main(String[] args) {
// 创建一个Dog对象数组
Dog[] dogs = { new Dog("Tom", 2), new Dog("Mikey", 1), new Dog("Jerry", 8) };
// 调用方法排序,并传入实现了Comparator接口的比较器DogAgeComparator
Arrays.sort(dogs, new DogAgeComparator());
System.out.println(Arrays.toString(dogs));
}
}
实现Comparator接口,并重写compare方法的比较器类DogAgeComparator,实现按年龄从小到大排序
import java.util.Comparator;
public class DogAgeComparator implements Comparator<Dog> {
@Override
public int compare(Dog o1, Dog o2) {
return o1.getAge() - o2.getAge();
}
}
如果用lambda表达式会更简单(●'◡'●)