本帖最後由 tonyh 於 2022-11-25 21:00 編輯
試定義一集合,集合中包含五個 Student 物件,再透過實作 Comparator 介面自訂比較器,分別完成「依座號遞增排序」及「依分數遞減排序」的比較方法,以 Collections 類別下的 sort() 方法搭配自訂的比較器,分別完成「依座號遞增排序」及「依分數遞減排序」之操作練習。
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- public class Ch01 {
- ArrayList<Student> stu=new ArrayList<Student>();
- Ch01()
- {
- stu.add(new Student(4, "大雄", 60));
- stu.add(new Student(1, "小叮噹", 90));
- stu.add(new Student(3, "宜靜", 100));
- stu.add(new Student(2, "阿福", 70));
- stu.add(new Student(5, "技安", 20));
- System.out.println("原始資料:");
- show();
- Collections.sort(stu, new MyComparator1()); //使用自定比較器來排序
- System.out.println("依座號遞增排序:");
- show();
- Collections.sort(stu, new MyComparator2());
- System.out.println("依分數遞減排序:");
- show();
- }
- void show()
- {
- System.out.println("座號\t姓名\t分數");
- System.out.println("-------------------");
- for(int i=0; i<stu.size(); i++)
- System.out.println(stu.get(i).num+"\t"+stu.get(i).name+"\t"+stu.get(i).score);
- System.out.println();
- }
- class MyComparator1 implements Comparator<Student>
- {
- @Override
- public int compare(Student o1, Student o2) { //遞增的比較方法
- return o1.num-o2.num;
- }
- }
- class MyComparator2 implements Comparator<Student>
- {
- @Override
- public int compare(Student o1, Student o2) { //遞減的比較方法
- return o2.score-o1.score;
- }
- }
- class Student //內部類別
- {
- int num, score;
- String name;
- Student(int n, String m, int s)
- {
- num=n;
- name=m;
- score=s;
- }
- }
- public static void main(String[] args) {
- new Ch01();
- }
- }
複製代碼 |