- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- public class P1 {
- ArrayList<Student> stu=new ArrayList<P1.Student>();
- P1(){
- 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 MyComprator1());
- System.out.println("依座號遞增排序:");
- show();
- Collections.sort(stu, new MyComprator2());
- System.out.println("依分數遞減排序:");
- show();
- }
- 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);
- }
- }
- class Student{
- int num,score;
- String name;
- Student(int n,String m,int s) {
- num=n;
- name=m;
- score=s;
- }
- }
- class MyComprator1 implements Comparator<Student>{
- @Override
- public int compare(Student o1, Student o2) {
- return o1.num-o2.num;
- }
-
- }
- class MyComprator2 implements Comparator<Student>{
- @Override
- public int compare(Student o1, Student o2) {
- return o2.score-o1.score;
- }
-
- }
- public static void main(String[] args) {
- new P1();
- }
- }
複製代碼 |