public class TestCallback {
public static void main(String[] args) {
Student[] stu = new Student[]{new Student("赵公民" , 99D) , new Student("冯光芒 ", 22D) , new Student("赵咕噜" , 80D)};
sort(stu);
for(int i = 0; i < stu.length;i++){
System.out.println(stu[i].name + "\t" + stu[i].score);
}
}
public static void sort(Student[] students){//手工写sort方法的实现过程
for(int i = 0;i < students.length - 1;i++){
Comparable com = (Comparable)students[i];//判断students是否调用Comparable接口
int n = com.compareTo(students[i+1]);
if(n > 0){
Student temp = students[i];//借用值替换目标
students[i] = students[i + 1];
students[i + 1] = temp;
}
}
}
}
class Student implements Comparable<Student>{
String name;
int age;
String sex;
double score;
public Student(String name , double score){
this.name = name;
this.score = score;
}
public int compareTo(Student s){//写和接口一样的方法,并且实现数值的判断返回 正整数,负整数或零
if(this.score > s.score){
return -1;
}
else if(this.score < s.score){
return 1;
}
else{
return 0;
}
}
}