返回列表 發帖
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;

  6. public class ha {
  7.         ArrayList<Student> stu=new ArrayList<ha.Student>();
  8.         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  9.         ha()
  10.         {
  11.                 stu.add(new Student(4, "大雄", 60));
  12.                 stu.add(new Student(1, "小叮噹", 90));
  13.                 stu.add(new Student(3, "宜靜", 100));
  14.                 stu.add(new Student(2, "阿福", 70));
  15.                 stu.add(new Student(5, "技安", 20));

  16.                 System.out.println("原始資料:");
  17.                 show();
  18.                 Collections.sort(stu, new MyComparator1());
  19.                 System.out.println("依座號遞增排序:");
  20.                 show();
  21.                 Collections.sort(stu, new MyComparator2());
  22.                 System.out.println("依座號遞減排序:");
  23.                 show();
  24.         }

  25.         class MyComparator1 implements Comparator<Student>
  26.         {
  27.                 public int compare(Student o1,Student o2)
  28.                 {
  29.                         return o1.num-o2.num;
  30.                 }
  31.         }
  32.         class MyComparator2 implements Comparator<Student>
  33.         {
  34.                 public int compare(Student o1,Student o2)
  35.                 {
  36.                         return o2.score-o1.score;
  37.                 }
  38.         }

  39.         void show()
  40.         {
  41.                 System.out.println("座號\t姓名\t分數");
  42.                 System.out.println("------------------------");
  43.                 for(Student s:stu)
  44.                 {
  45.                         System.out.println(s.num+"\t"+s.name+"\t"+s.score);
  46.                 }
  47.                 System.out.println();
  48.         }

  49.         class Student
  50.         {
  51.                 int num, score;
  52.                 String name;

  53.                 Student(int num, String n, int s)
  54.                 {
  55.                         this.num=num;
  56.                         name=n;
  57.                         score=s;
  58.                 }
  59.         }

  60.         public static void main(String[] args) throws Exception {
  61.                 new ha();
  62.         }
  63. }
複製代碼

TOP

返回列表