什么是比较器?其实是利用 系统的比较函数 arrays.sort(T[],templements),这个接口函数,重新定义接口函数的比较函数而实现的.
import java.util.Arrays;
import java.util.Comparator;
/**
* 〈一句话功能简述〉<br>
* 〈比较器〉
*
* @author Administrator
* @create 2019/5/16
* @since 1.0.0
*/
public class ComparaStruct {
public static class Student {
public String name;
public int id;
public int age;
public Student(String name , int id , int age) {
this.name = name;
this.id = id;
this.age = age;
}
}
public static void printfStudent(Student[] students) {
for (Student student : students) {//打印数组中的信息 :代表是从数组中
System.out.println("name : " + student.name + " id : " + student.id + " age : " + student.age);
}
System.out.println("=====================");
}
public static class idAsc implements Comparator<Student> {//创建一个静态类 实现比较的接口 重新定义比较函数
@Override//重覆盖
public int compare(Student s1 , Student s2) {
return s1.id - s2.id;
}
}
public static void main(String[] args) {
Student student1 = new Student("Li" , 2 , 17);
Student student2 = new Student("wang" , 1 , 21);
Student student3 = new Student("zhang" , 3 , 24);
Student[] students = new Student[]{student1 , student2 , student3};
printfStudent(students);
Arrays.sort(students , new idAsc());//实现自定义 数据类型 的排序
printfStudent(students);
}
}