此接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的compareTo方法被称为他的自然比较方法
方法
int comparaTo(T o) 比较此对象与指定对象的顺序
重写comparaTo(T o)方法修改排序规则
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
}
public Student(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 int compareTo(Student o) {
// return 0; // 两个元素相同
// 自定义排序规则 ,按照年龄进行排序
// this 参数 o 参数
// this.getAge() - o.getAge() // 升序
// o.getAge() - this.getAge() // 降序
return this.getAge() - o.getAge();
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Demo02Collections {
public static void main(String[] args) {
ArrayList<Student> list03 = new ArrayList<>();
list03.add(new Student("李四", 34));
list03.add(new Student("小王",30));
list03.add(new Student("早咧", 21));
list03.add(new Student("小刘",27));
list03.add(new Student("一号", 18));
System.out.println(list03);
// 排序
Collections.sort(list03);
}