java中自定义比较器
学生类有三个属性,按照其中的ID属性,进行降序和升序排列
package lesson01;
import java.util.Arrays;
import java.util.Comparator;
public class demo04_Comparator {
public static void main(String[] args) {
student s1 = new student("A", 2, 23);
student s2 = new student("B", 1, 21);
student s3 = new student("C", 3, 22);
student stuents[] = { s1, s2, s3 }; // 自定义学生数组,将学生对象扔进去
printStudents(stuents);
Arrays.sort(stuents, new IdAscendingComparator());
printStudents(stuents);
}
public static void printStudents(student[] students) {
for (student student : students) {
System.out.println("Name : " + student.name + ", Id : " + student.id + ", Age : " + student.age);
}
System.out.println("===========================");
}
}
// 自定义升序比较类,实现比较规则
class IdAscendingComparator implements Comparator<student> {
// 升序
@Override
public int compare(student s1, student s2) {
return s1.id - s2.id;
}
}
// 自定义降序比较类,实现比较规则
class IdDescendingComparator implements Comparator<student> {
// 降序
@Override
public int compare(student s1, student s2) {
return s2.id - s1.id;
}
}
class student {
String name;
int id;
int age;
public student(String name, int id, int age) {
super();
this.name = name;
this.id = id;
this.age = age;
}
}
Name : B, Id : 1, Age : 21
Name : A, Id : 2, Age : 23
Name : C, Id : 3, Age : 22
====================
Name : C, Id : 3, Age : 22
Name : A, Id : 2, Age : 23
Name : B, Id : 1, Age : 21
====================