返回列表 發帖
  1. import java.util.ArrayList;
  2. import java.util.Collection;
  3. import java.util.Collections;
  4. import java.util.Comparator;


  5. public class T2 {
  6.         ArrayList<Student> stu=new ArrayList<T2.Student>();
  7.         T2(){
  8.                 stu.add(new Student(4,"大熊",60));
  9.                 stu.add(new Student(1,"多拉A夢",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.         System.out.println("座號遞增:");
  16.         Collections.sort(stu,new MyComparator1());
  17.         show();
  18.         System.out.println("分數遞減:");
  19.         Collections.sort(stu,new MyComparator2());
  20.         show();
  21.         }
  22.         class MyComparator1 implements Comparator<Student>{
  23.                 public int compare(Student o1,Student o2) {
  24.                         return o1.num-o2.num;
  25.                 }
  26.                
  27.         }
  28.         class MyComparator2 implements Comparator<Student>{
  29.                 public int compare(Student o1,Student o2) {
  30.                         return o2.score-o1.score;
  31.                 }
  32.                
  33.         }
  34.         void show()
  35.     {
  36.             System.out.println("座號\t姓名\t分數");
  37.             System.out.println("-------------------");
  38.             for(int i=0; i<stu.size(); i++)
  39.                     System.out.println(stu.get(i).num+"\t"+stu.get(i).name+"\t"+stu.get(i).score);
  40.             System.out.println();
  41.     }
  42.         class Student{
  43.                 int num,score;
  44.                 String name;
  45.                 Student(int n, String m, int s)
  46.         {
  47.                 num=n;
  48.                 name=m;
  49.                 score=s;
  50.         }
  51.         }
  52.         public static void main(String[] args) {
  53.                 new T2();

  54.         }

  55. }
複製代碼
hahahahahahahaha

TOP

返回列表