返回列表 發帖

自訂排序 (一)

本帖最後由 tonyh 於 2022-11-25 17:58 編輯

試定義一集合,集合中包含五個 Student 物件,再透過實作 Comparator 介面自訂比較器,分別完成「依分數遞減排序」及「依座號遞增排序」的比較方法,以 Collections 類別下的 sort() 方法搭配自訂的比較器,分別完成「依分數遞減排序」及「依座號遞增排序」之操作練習。


  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;

  4. public class Ch01 {

  5.         ArrayList<Student> stu=new ArrayList<Student>();

  6.         Ch01()
  7.         {
  8.                 stu.add(new Student(4, "大雄", 60));
  9.                 stu.add(new Student(1, "小叮噹", 90));
  10.                 stu.add(new Student(3, "宜靜", 100));
  11.                 stu.add(new Student(2, "阿福", 70));
  12.                 stu.add(new Student(5, "技安", 20));

  13.                 System.out.println("原始資料:");
  14.                 show();

  15.                 Collections.sort(stu, new MyComparator1());   //使用自定比較器來排序

  16.                 System.out.println("依座號遞增排序:");
  17.                 show();

  18.                 Collections.sort(stu, new MyComparator2());

  19.                 System.out.println("依分數遞減排序:");
  20.                 show();
  21.         }

  22.         void show()
  23.         {
  24.                 System.out.println("座號\t姓名\t分數");
  25.                 System.out.println("-------------------");
  26.                 for(int i=0; i<stu.size(); i++)
  27.                         System.out.println(stu.get(i).num+"\t"+stu.get(i).name+"\t"+stu.get(i).score);
  28.                 System.out.println();
  29.         }

  30.         class MyComparator1 implements Comparator<Student>
  31.         {
  32.                 @Override
  33.                 public int compare(Student o1, Student o2) {  //遞增的比較方法
  34.                         return o1.num-o2.num;
  35.                 }       
  36.         }

  37.         class MyComparator2 implements Comparator<Student>
  38.         {
  39.                 @Override
  40.                 public int compare(Student o1, Student o2) {  //遞減的比較方法
  41.                         return o2.score-o1.score;
  42.                 }       
  43.         }

  44.         class Student   //內部類別
  45.         {
  46.                 int num, score;
  47.                 String name;

  48.                 Student(int n, String m, int s)
  49.                 {
  50.                         num=n;
  51.                         name=m;
  52.                         score=s;
  53.                 }
  54.         }

  55.         public static void main(String[] args) {
  56.                 new Ch01();
  57.         }
  58. }
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊

返回列表