很多情况下,我们需要对数据进行排序,但是java自带的比较器只能比较基本数据类型,比如我们自己定义一个Student类,如果用默认的Array.sort()方法进行排序,他会按照内存地址进行排序,那么这个排序毫无意义,此时我们就需要自己定义一个比较器,按照我们想要的比较方式来进行排序。
我们需要定义一个比较器,实现java.util.Comparator接口,会需要重写一个compare()方法,如下
public static class CustomeComparator implements Comparator<Student>{
// 根据学生成绩进行排序
@Override
public int compare(Student st1, Student st2) {
return st1.socre-st2.socre;
}
}
这就是一个基本的比较器,其返回值分三种
负数: 前者 < 后者
0: 两者相等
正数: 前者 > 后者
public static void main(String[] args) {
Student student1 = new Student("A", 18, 76);
Student student2 = new Student("B", 22, 85);
Student student3 = new Student("C", 31, 64);
Student[] students = new Student[] { student1, student2, student3 };
for (Student student : students) {
System.out.println(student);
}
System.out.println("------ 排序后 --------");
Arrays.sort(students, new CustomeComparator());
for (Student student : students) {
System.out.println(student);
}
}
使用的时候直接把需要排序的数组和自定义比较器丢进sort()即可,可以看看打印前后的顺序。对Array.sort()和Collections.sort()不太了解的朋友可以去自行百度,我这里不做过多解释。
Student [name=A, age=18, socre=76]
Student [name=B, age=22, socre=85]
Student [name=C, age=31, socre=64]
------ 排序后 --------
Student [name=C, age=31, socre=64]
Student [name=A, age=18, socre=76]
Student [name=B, age=22, socre=85]
一个简单的比较器就完成了,可以根据自己的需求进行定制。
后面贴出完整代码:
import java.util.Arrays;
import java.util.Comparator;
public class MyComparator {
public static class Student{
public String name;
public int age;
public int socre;
public Student(String name, int age, int socre) {
super();
this.name = name;
this.age = age;
this.socre = socre;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", socre=" + socre + "]";
}
}
public static class CustomeComparator implements Comparator<Student>{
// 根据学生成绩进行排序
@Override
public int compare(Student st1, Student st2) {
return st1.socre-st2.socre;
}
}
public static void main(String[] args) {
Student student1 = new Student("A", 18, 76);
Student student2 = new Student("B", 22, 85);
Student student3 = new Student("C", 31, 64);
Student[] students = new Student[] { student1, student2, student3 };
for (Student student : students) {
System.out.println(student);
}
System.out.println("------ 排序后 --------");
Arrays.sort(students, new CustomeComparator());
for (Student student : students) {
System.out.println(student);
}
}
}