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

  7. public class Stacking {
  8.         ArrayList<Student> stu=new ArrayList<>();
  9.         Stacking()
  10.     {
  11.             stu.add(new Student(4, "A", 60));
  12.             stu.add(new Student(1, "B", 90));
  13.             stu.add(new Student(3, "C", 100));
  14.             stu.add(new Student(2, "D", 70));
  15.             stu.add(new Student(5, "E", 20));
  16.            
  17.             System.out.println("原始資料: ");
  18.             show();           
  19.             Collections.sort(stu, new MyComparator());   
  20.             System.out.println("依座號遞增排序: ");
  21.             show();           
  22.             Collections.sort(stu, new MyComparator2());           
  23.             System.out.println("依分數遞減排序: ");
  24.             show();
  25.     }
  26.    
  27.     void show()
  28.     {
  29.             System.out.println("num\tname\tscore");
  30.             System.out.println("----------------------");
  31.             for(int i=0; i<stu.size(); i++)
  32.                 System.out.println(stu.get(i).num+"\t"+stu.get(i).name+"\t"+stu.get(i).score);
  33.         System.out.println();
  34.     }
  35.    
  36.     class MyComparator implements Comparator<Student>
  37.     {
  38.             public int compare(Student o1, Student o2)
  39.             {
  40.                     return o1.num-o2.num;
  41.             }
  42.     }
  43.    
  44.     class MyComparator2 implements Comparator<Student>
  45.     {
  46.             public int compare(Student o1, Student o2)
  47.             {
  48.                     return o2.score-o1.score;
  49.             }
  50.     }
  51.         class Student
  52.         {
  53.                 int num, score;
  54.                 String name;
  55.                 Student(int num, String name,int score)
  56.                 {
  57.                         this.num=num;
  58.                         this.name=name;
  59.                         this.score=score;
  60.                 }
  61.         }
  62.         public static void main(String[] args) throws IOException, Exception {
  63.                 new Stacking();
  64.         }

  65. }
複製代碼
我是眾神之王XXX  I love you
0000000000

TOP

返回列表