- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Comparator;
- public class Ch01 {
- ArrayList<Student> stu=new ArrayList<>();
- Ch01()
- {
- 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 Mycomparator2());
- System.out.println("依座號排序:");
- show();
- Collections.sort(stu,new Mycomparator1());
- System.out.println("依座號遞減:");
- show();
- }
- 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 Mycomparator2 implements Comparator<Student>
- {
- public int compare(Student o1,Student o2) {
- return o1.num-o2.num;
- }
- class Mycomparator1 implements Comparator<Student>
- {
- public int compare(Student o1,Student o2) {
- return o2.num-o1.num;
- }
- }
- 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 Ch01();
- }
- }
複製代碼 |