一般情况下我们都是对数字或者字符串排序,如何对对象进行排序呢?例如Order对象Student对象,那么就需要Order对象、Student对象实现Comparable接口
按照年龄从大到小排序
@Getter
@Setter
@ToString
public class Student implements Comparable<Student> {
private int age;
private String name;
private int hight;
@Override
public int compareTo(Student o) {
return this.age-o.getAge();
}
}
public static void main(String[] args) {
Student student = new Student();
student.setAge(10);
student.setHight(186);
student.setName("zhangsan");
Student student1 = new Student();
student1.setAge(18);
student1.setHight(165);
student1.setName("lisi");
List<Student> list = new ArrayList<>();
list.add(student);
list.add(student1);
//默认按照年龄从小到大排序,因为学生类实现了Comparable的compareTo方法
Collections.sort(list);
System.out.println("默认按照年龄从小到大排序:"+list);
//按照默认排序找到年龄最大的
System.out.println("按照默认排序找到年龄最大的:"+getMax(student1, student));
//身高按照从小到大排序
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getHight()-o2.getHight();
}
});
System.out.println("身高按照从小到大排序 :"+list);
}
public static Comparable getMax(Comparable o1, Comparable o2) {
int i = o1.compareTo(o2);
if (i > 1) {
return o1;
} else {
return o2;
}
}
网上有说 Comparable 和Comparator用到了策略模式,设计模式不精明的我还没体会粗来 ,在我看来只是用到了多态