- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Collections;
- import java.util.Comparator;
- public class T2 {
- ArrayList<Student> stu=new ArrayList<T2.Student>();
- T2(){
- stu.add(new Student(4,"大熊",60));
- stu.add(new Student(1,"多拉A夢",90));
- stu.add(new Student(3,"靜香",100));
- stu.add(new Student(2,"小夫",70));
- stu.add(new Student(5,"胖虎",20));
- System.out.println("原始資料:");
- show();
- System.out.println("座號遞增:");
- Collections.sort(stu,new MyComparator1());
- show();
- System.out.println("分數遞減:");
- Collections.sort(stu,new MyComparator2());
- 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(int i=0; i<stu.size(); i++)
- System.out.println(stu.get(i).num+"\t"+stu.get(i).name+"\t"+stu.get(i).score);
- System.out.println();
- }
- 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) {
- new T2();
- }
- }
複製代碼 |