实现比较器有两种方法
第一种、一些类自己实现Comparable,笔试用的较少;
第二种、人为定义对类的比较。实现Comparator接口。
举例 有三个学生 我自创了学术类,mian生成了三个学生A\B\C要将他们按照id排序,在重新compare方法中,只要负数就放放前面,程序会自动帮你生成的。
import java.util.Arrays;
import java.util.Comparator;
import basic_class_01.Code_09_Comparator.Student;
public class Code_09_Comparator2 {
public static class Student{
String name;
int id;
int age;
public Student(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
}
public static class IdComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.id - o2.id;
}
}
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("===========================");
}
public static void main(String[] args) {
Student student1 = new Student("A", 9, 23);
Student student2 = new Student("B", 2, 21);
Student student3 = new Student("C", 3, 22);
Student[] stus = new Student[] {student1,student2,student3};
Arrays.sort(stus, new IdComparator());
printStudents(stus);
}
}