代码语言:javascript复制
package snippet;
import java.util.Arrays;
import java.util.Comparator;
public class ComparatorUse {
public static void main(String[] args) {
Student[] persons = new Student[5];
persons[0] = new Student("tom", 1, 88, 45);
persons[1] = new Student("jack", 6, 80, 12);
persons[2] = new Student("bill", 4, 68, 21);
persons[3] = new Student("kandy", 2, 98, 34);
persons[4] = new Student("lily", 5, 94, 20);
System.out.println("排序前的数据:");
for (Student student : persons) {
System.out.println(student);
}
//这里是关键
Arrays.sort(persons, new SortByNumber());
System.out.println("根据学生编号由低到高排序:");
for (Student student : persons) {
System.out.println(student);
}
//这里是关键
Arrays.sort(persons, new SortByScore());
System.out.println("根据学生成绩由高到低排序:");
for (Student student : persons) {
System.out.println(student);
}
}
//这里是关键
static class SortByNumber implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.getNumber() - o2.getNumber();
}
}
//这里是关键
static class SortByScore implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o2.getScore() - o1.getScore();
}
}
}
输出:
代码语言:javascript复制排序前的数据:
Student[name:tom,age:45,number:1,score:88]
Student[name:jack,age:12,number:6,score:80]
Student[name:bill,age:21,number:4,score:68]
Student[name:kandy,age:34,number:2,score:98]
Student[name:lily,age:20,number:5,score:94]
根据学生编号由低到高排序:
Student[name:tom,age:45,number:1,score:88]
Student[name:kandy,age:34,number:2,score:98]
Student[name:bill,age:21,number:4,score:68]
Student[name:lily,age:20,number:5,score:94]
Student[name:jack,age:12,number:6,score:80]
根据学生成绩由高到低排序:
Student[name:kandy,age:34,number:2,score:98]
Student[name:lily,age:20,number:5,score:94]
Student[name:tom,age:45,number:1,score:88]
Student[name:jack,age:12,number:6,score:80]
Student[name:bill,age:21,number:4,score:68]
student类:
代码语言:javascript复制package snippet;
class Student {
private String name;
private int number;
private int score;
private int age;
public Student(String name,int number,int score,int age){
this.name = name;
this.number = number;
this.score = score;
this.age = age;
}
@Override
public String toString() {
return "Student[name:" name ",age:" age ",number:" number ",score:" score "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}