- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- public class ha {
- ArrayList<Student> stu=new ArrayList<ha.Student>();
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- ha()
- {
- stu.add(new Student(4, "大雄", 60));
- stu.add(new Student(1, "小叮噹", 90));
- stu.add(new Student(3, "宜靜", 100));
- stu.add(new Student(2, "阿福", 70));
- stu.add(new Student(5, "技安", 20));
- System.out.println("原始資料:");
- show();
- Collections.sort(stu, new MyComparator1());
- System.out.println("依座號遞增排序:");
- show();
- Collections.sort(stu, new MyComparator2());
- System.out.println("依座號遞減排序:");
- show();
- }
- class MyComparator1 implements Comparator<Student>
- {
- public int compare(Student o1,Student o2)
- {
- return o1.num-o2.num;
- }
- }
- class MyComparator2 implements Comparator<Student>
- {
- public int compare(Student o1,Student o2)
- {
- return o2.score-o1.score;
- }
- }
- void show()
- {
- System.out.println("座號\t姓名\t分數");
- System.out.println("------------------------");
- for(Student s:stu)
- {
- System.out.println(s.num+"\t"+s.name+"\t"+s.score);
- }
- System.out.println();
- }
- class Student
- {
- int num, score;
- String name;
- Student(int num, String n, int s)
- {
- this.num=num;
- name=n;
- score=s;
- }
- }
- public static void main(String[] args) throws Exception {
- new ha();
- }
- }
複製代碼 |