本帖最後由 tonyh 於 2021-7-10 15:06 編輯
承上題,以陣列取代原本的集合,陣列中包含五個 Student 物件,以 Arrays 類別下的 sort() 方法搭配自定的比較器,分別完成「依分數遞減排序」及「依座號遞增排序」之操作練習。
 - import java.util.Arrays;
- import java.util.Comparator;
- public class Ch02 {
- Student stu[]=new Student[5];
- Ch02()
- {
- stu[0]=new Student(4, "大雄", 60);
- stu[1]=new Student(1, "小叮噹", 90);
- stu[2]=new Student(3, "宜靜", 100);
- stu[3]=new Student(2, "阿福", 70);
- stu[4]=new Student(5, "技安", 20);
- System.out.println("原始資料:");
- show();
- Arrays.sort(stu, new MyComparator1());
- System.out.println("依分數遞減排序:");
- show();
- Arrays.sort(stu, new MyComparator2());
- System.out.println("依座號遞增排序:");
- show();
- }
- void show()
- {
- System.out.println("座號\t姓名\t分數");
- System.out.println("-------------------");
- for(int i=0; i<stu.length; i++)
- System.out.println(stu[i].num+"\t"+stu[i].name+"\t"+stu[i].score);
- System.out.println();
- }
- class Student
- {
- int num, score;
- String name;
- Student(int num, String name, int score) //建構子; 建構函式; 建構方法
- {
- this.num=num;
- this.name=name;
- this.score=score;
- }
- }
- class MyComparator1 implements Comparator<Student> //泛型
- {
- @Override
- public int compare(Student o1, Student o2) {
- return o2.score-o1.score;
- }
- }
- class MyComparator2 implements Comparator<Student> //泛型
- {
- @Override
- public int compare(Student o1, Student o2) {
- return o1.num-o2.num;
- }
- }
- public static void main(String[] args) {
- new Ch02();
- }
- }
複製代碼 |