- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.Collections;
- public class cccc {
- ArrayList<Student> sa=new ArrayList<Student>();
- cccc()
- {
- sa.add(new Student(4, "大雄", 60));
- sa.add(new Student(1, "小叮噹", 90));
- sa.add(new Student(3, "宜靜", 100));
- sa.add(new Student(2, "阿福", 70));
- sa.add(new Student(5, "技安", 20));
- System.out.println("原始資料:");
- show();
-
- Collections.sort(sa, new C());
- System.out.println("依座號遞增排序:");
- show();
-
- Collections.sort(sa, new C2());
- System.out.println("依分數遞減排序:");
- show();
- }
- void show()
- {
- System.out.println("座號\t姓名\t分數");
- System.out.println("---------------------");
- for(int i=0;i<sa.size();i++)
- System.out.println(sa.get(i).num+"\t"+sa.get(i).name+"\t"+sa.get(i).score);
- System.out.println();
- }
- class C implements Comparator<Student>
- {
- public int compare(Student s1, Student s2)
- {
- return s1.num-s2.num;
- }
- }
- class C2 implements Comparator<Student>
- {
- public int compare(Student s1, Student s2)
- {
- return s2.score-s1.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) throws Exception{
- new cccc();
- }
- }
複製代碼 |