自己定义需要比较的东西
1 public class Bokeyuan { 2 public static class Student{ 3 public String name; 4 public int id; 5 public int age; 6 7 public Student (String name,int id,int age) { 8 this.name=name; 9 this.id=id; 10 this.age=age; 11 } 12 } 13 14 public static class IdAscendingComparator implements Comparator<Student>{//1.Id...自己定义的比较器;2.Comparator 继承接口,接口内放置自己定义的想要比较的东西;3.把定义好的类放到main函数的调用类上 15 16 @Override 17 public int compare(Student arg0, Student arg1) { 18 // TODO 自动生成的方法存根 19 return arg0.id-arg1.id;//怎么比较???1.当返回的数值为负数,前面的数值更小;2.返回的为正数,后面的参数更小,3.返回的为0,相等 20 } 21 } 22 public static class IdDescendingComparator implements Comparator<Student>{ 23 24 @Override 25 public int compare(Student arg0, Student arg1) { 26 // TODO 自动生成的方法存根 27 return arg1.id-arg0.id;//降序 28 } 29 } 30 public static class AgeScendingComparator implements Comparator<Student>{ 31 32 @Override 33 public int compare(Student arg0, Student arg1) { 34 // TODO 自动生成的方法存根 35 return arg0.age-arg1.age;//升序 36 } 37 } 38 public static class AgeDescendingComparator implements Comparator<Student>{ 39 40 @Override 41 public int compare(Student arg0, Student arg1) { 42 // TODO 自动生成的方法存根 43 return arg1.age-arg0.age;//降序 44 } 45 } 46 public static void printStudent (Student[] students) { 47 for(Student student:students) {//输出函数 48 System.out.println("Name: "+student.name+",Id: "+student.id+",Age:"+student.age); 49 System.out.println("====================================="); 50 } 51 } 52 53 public static void main (String[] args) { 54 Student student1 =new Student("A",1,25); 55 Student student2 =new Student("B",2,23); 56 Student student3 =new Student("C",3,24); 57 //建立数组,把学生1,2,3放进去 58 Student[] students =new Student[] { 59 student3,student2,student1 60 }; 61 //Arrays.sort调用系统函数 有意义的情况:1.数组2.写入自己定义的比较器,不写的话,是单纯调用sort(students)按照内存地址排序毫无意义。例如,基础类型按照数值大小排序,从小到大。 62 printStudent(students); 63 Arrays.sort(students,new IdAscendingComparator()); 64 65 printStudent(students); 66 Arrays.sort(students,new IdDescendingComparator()); 67 68 printStudent(students); 69 Arrays.sort(students,new AgeDescendingComparator()); 70 71 printStudent(students); 72 Arrays.sort(students,new AgeScendingComparator()); 73 74 } 75 }