通过Comparable接口实现类的自定义排序
简介:通过给类继承接口的方式来 重写compareTo方法 然后自定义排序规则,在合作开发的过程中 每个人更能很好的负责自己模块,提高开发效率。
import java.util.Arrays;
import java.util.Comparator;
public class Main {
// 通过给类继承接口的方式来 重写compareTo方法 然后自定义排序规则
static class Student implements Comparable<Student>{
public int age;
public String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
// 重写toString方法方便显示
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
// 这样的好处在于 在合作开发的过程中 每个人更能很好的负责自己模块
@Override
public int compareTo(Student o) {
// compareTo方法比较原理在于用本类的this对象与 传入的o对象之间进行比较
int num = 0;
if (this.age >= o.age) num = -1;
else num = 1;
return num;
}
}
public static void main(String[] args) {
// 对于普通数组的排序
Student [] a= new Student [5];
a[0] = new Student(10, "李华");
a[1] = new Student(9, "李明");
a[2] = new Student(12, "李肖");
a[3] = new Student(1, "李大");
a[4] = new Student(5, "李页");
// 对Student类按照年龄升序排序 可以不传入比较方法
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
// Student{age=12, name='李肖'} Student{age=10, name='李华'} Student{age=9, name='李明'} Student{age=5, name='李页'} Student{age=1, name='李大'}
}
}