標籤:arrays core object 排列 gets this 題目 add des
http://www.verejava.com/?id=169931036202101
/** 知識點: 比較類 Comparator 題目: 將某班學生按數學成績從小到大排序 思路: 1. 抽象出類: 1.1 班級(ClassSet) 1.2 學生(Student) 2. 找出類別關係: 2.1 學生 屬於 班級 Student -> ClassSet(多對1) 3. 找出類屬性: 3.1 ClassSet(班級名稱,班級人數) 3.2 Student(學生名稱,數學成績) 4. 找出類方法: 4.1 學生添加到班級 ClassSet{addStudent(Student s)} 4.2 學產生績從小到大排序 ClassSet{sortByScore()}*/import java.util.Arrays;import java.util.Comparator;public class TestComparator{ public static void main(String[] args) { //執行個體化4G班級 ClassSet c=new ClassSet("4G",4); //新增學生 c.addStudent(new Student("李明",90)); c.addStudent(new Student("李浩",80)); c.addStudent(new Student("王濤",95)); c.addStudent(new Student("張勝",70)); //獲得4G班級學生數組集合 Student[] students=c.getStudents(); //輸出學生資訊 for(Student s:students) { if(s!=null) System.out.println(s.getName()+","+s.getMathScore()); } System.out.println("\n根據學產生績升序排序"); Arrays.sort(students,new StudentAscComparator()); for(Student s:students) { if(s!=null) System.out.println(s.getName()+","+s.getMathScore()); } System.out.println("\n根據學產生績降序排序"); Arrays.sort(students,new StudentDescComparator()); for(Student s:students) { if(s!=null) System.out.println(s.getName()+","+s.getMathScore()); } }}class ClassSet{ private String className;//班級名稱 private int maxSize;//班級學生人數 private int currentSize;//當前多少學生 private Student[] students;//所有學生的數組 public ClassSet(String className,int maxSize) { this.className=className; this.maxSize=maxSize; students=new Student[maxSize]; } public Student[] getStudents() { return this.students; } /** 新增學生 */ public void addStudent(Student s) { for(int i=0;i<students.length;i++) { if(students[i]==null) { students[i]=s; currentSize++; break; } } } }class Student { private String name;//學生姓名 private int mathScore;//數學成績 public Student(String name,int mathScore) { this.name=name; this.mathScore=mathScore; } public String getName() { return this.name; } public void setName(String name) { this.name=name; } public int getMathScore() { return this.mathScore; } public void setMathScore(int mathScore) { this.mathScore=mathScore; }}/** 學生升序排列*/class StudentAscComparator implements Comparator{ public int compare(Object o1,Object o2) { if((o1 instanceof Student)&&(o2 instanceof Student)) { Student s1=(Student)o1; Student s2=(Student)o2; if(s1.getMathScore()>s2.getMathScore()) return 1; if(s1.getMathScore()<s2.getMathScore()) return -1; } return 0; }}/** 學生降序排列*/class StudentDescComparator implements Comparator{ public int compare(Object o1,Object o2) { if((o1 instanceof Student)&&(o2 instanceof Student)) { Student s1=(Student)o1; Student s2=(Student)o2; if(s1.getMathScore()>s2.getMathScore()) return -1; if(s1.getMathScore()<s2.getMathScore()) return 1; } return 0; }}
http://www.verejava.com/?id=169931036202101
Java 常用類庫 之 比較介面 Comparator