Compareable接口
类的自然排序接口,必须重写public int compareTo(Object o)方法
步骤:1.类实现Compareable接口,重写compareTo(Object o)方法。
2.编写比较规则
/ 学生类
public class Student implements Compareable {
private int number; / 学号
private String name; / 姓名
private String sex; / 性别
Student(){}
Student(int number, String name, String sex) {
this.number = number;
this.name = name;
this.sex = sex;
}
/ Setter和Getter方法省略没写
...
}
@Override
public int compareTo(Object o) {
Student stu = (Student)o;
/ 按照学号进行排序
if (this.number == stu.number) {
return 0;
} else if (this.number > stu.number) {
retunr 1;
} else {
retunr -1;
}
}
/ 测试类
public class Test {
public static void main(String[] args) {
List<Student> list = new ArrayList();
Student s1 = new Student(2, "微微", "女");
Student s2 = new Student(9, "一笑", "男");
Student s3 = new Student(7, "很倾城", "女");
list.add(s1);
list.add(s2);
list.add(s3);
/ 按照学号进行升序排序
Collections.sort(list);
for (Student stu: list) {
System.out.println(stu.getNumber() + stu.getName() +stu.getSex());
}
}
}
我寻见一片海 碧蓝且耀着光
大片船只航行其上 都向着远方
Shared by Foriver_江河