系统中自带的Arrays.sort()默认比较器是从小到大排序的,但是我们有时候需要从大到小排序,又或者我们需要比较对象,这时候就需要用到比较器了。
代码中比较器就是一个类重载了Comparator中的compare方法
public static class Acomp implements Comparator<Integer>{
//
@Override
public int compare(Integer arg0, Integer arg1) {
// TODO Auto-generated method stub
//返回负数的话,就第一个参数排在前面
//返回正数的话,第一个参数排在后面
//返回0,无所谓谁前面。
return arg1-arg0;
}
}
在使用的时候,只需要使用Arrays.sort(arr,new Acomp())就行
public static void main(String[] args) {
Integer[] a = {1,2,7,4,5};
Arrays.sort(a, new Acomp());
for(int i:a) {
System.out.println(i);
}
}
唯一需要注意的一个点就行,compare方法传递的必需是一个object对象,也就是说基本类型是不可以的,所以定义数组的使用包装类Integer。
对象的比较也是一样的
public static class StudentComp implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.id-o2.id;
}
}
这样在排序的时候就是id小的排在前面。
public static void main(String[] args) {
Student s1 = new Student("yf1",42,20);
Student s2 = new Student("yf2",22,20);
Student s3 = new Student("yf3",32,20);
Student[] students = {s1,s2,s3};
Arrays.sort(students,new StudentComp());
for(Student s:students) {
System.out.println(s);
}
}
比较器还可以对有序的结构进行比较,比如堆结构
public static class Acomp implements Comparator<Integer>{
@Override
public int compare(Integer arg0, Integer arg1) {
// TODO Auto-generated method stub
//返回负数的话,就第一个参数应该放在上面
//返回正数的话,第一个参数应该放在下面
//返回0,无所谓谁上下。
return arg1-arg0;
}
}
public static void main(String[] args) {
//PriorityQueue默认是小根堆,
PriorityQueue<Integer> heap = new PriorityQueue(new Acomp());
heap.add(2);
heap.add(3);
heap.add(1);
heap.add(4);
while(!heap.isEmpty()) {
System.out.println(heap.poll());
}
}
这样排出来之后就是大根堆。