比較器Comparator
阿新 • • 發佈:2019-01-10
Comparator介面
java中有內建的排序,Arrays.sort(),現在我有一個Student類,類中三個成員變數name,id,age,我現在想以age作為參考進行升序排序,應該如何做,很簡單,只需要自己定義一個類實現Comparator介面即可
import java.util.*;
class Student {
String name;
int id,age;
Student(String name,int id,int age) {
this.name = name;
this.id = id;
this.age = age;
}
}
public class ComparetorTest {
public static class MyCompara implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.age - s2.age;
}
}
public static void main(String[] args) {
Student s1 = new Student("A",1,22);
Student s2 = new Student("B",3,23);
Student s3 = new Student("C",2,21);
Student[] student = new Student[] {s1,s2,s3};
Arrays.sort(student, new MyCompara());
for(int i = 0;i < student.length;i++)
System.out.println(student[i].name + " " + student[i].id + " " + student[i].age);
}
}