abstract class Compare implements Comparator{
//抽象方法
abstract public int compare(Object o1, Object o2);
}
//学号比较器接口,继承抽象类
class CompareByStuId extends Compare{
//比较学号
public int compare(Object o1, Object o2) {
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.stuId.compareTo(s2.stuId);
}
}
public class MainTest {
public static void main(String[] args) {
Student[] stus;
stus=readStudentFile();
ArrayList stuList;
String nameId; //保存学号或者姓名
//按学号升序排序输出,抽象父类的引用,子类的对象
Compare cbn=new CompareByStuId();
stuList=sort(stus,cbn);
for (int i = 0; i < stus.length; i++) {
stus[i]=(Student)stuList.get(i);
}
printData(stus);//输出所有
}
//根据传入的是Compare的哪个子类,按照学号排序的方法,
public static ArrayList sort(Student[] stus,Compare cmp){
ArrayList stuList=new ArrayList();
for (int i = 0; i < stus.length; i++) {
stuList.add(stus[i]);
}
Collections.sort(stuList,cmp);
return stuList;
}
}
public class Student {
//属性
String stuId;
String stuName;
String sex;
String college;
int[] scores=new int[10];
int avg;
//构造方法
Student(){
}
Student(String stuId,String stuName,String sex,String college){
this.stuId=stuId;
this.stuName=stuName;
this.sex=sex;
this.college=college;
}
}
使用集合排序,Collections.sort(stuList,cmp);
关键的代码是排序接口:
abstract class Compare implements Comparator{
//抽象方法
abstract public int compare(Object o1, Object o2);
}
//学号比较器接口,继承抽象类
class CompareByStuId extends Compare{
//比较学号
public int compare(Object o1, Object o2) {
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.stuId.compareTo(s2.stuId);
}
}