利用JAVA Comparator接口实现数组排序

时间:2022-05-20 22:39:48

示例,对自定义数据类型进行排序。

ArrayList<Struct>result=new ArrayList<Struct>();

Collections.sort(result,new Comparator<Object>(){
@Override
public int compare(Object arg0, Object arg1){
Struct a = (Struct) arg0;
Struct b = (Struct) arg1;
if ( a.getNum()<b.getNum() ){
return 1;
}
else{
<span style="white-space:pre"></span>if(a.getNum()==b.getNum()){
return 0;
}else{
return -1;
}
}
}
});
如上所示,只需要规定相比较的规则,JAVA就会自动排序,很方便。

-----------------------------------------------------------------------------------------

源码分析:

/**
* Compares its two arguments for order. Returns a negative integer,
* zero, or a positive integer as the first argument is less than, equal
* to, or greater than the second.
**/
API中写明,如果参数1比参数2小,返回-1,相等返回0,否则返回1.

那么sort方法是如何具体的执行比较器规则的呢?

我先找到了collections源码,发现它的sort方法:

public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
主要工作还是在 
Arrays.sort(a);
于是,我再找到Arrays源码,如下:

public static <T> void sort(T[] a, Comparator<? super T> c) {
T[] aux = (T[])a.clone();
if (c==null)
mergeSort(aux, a, 0, a.length, 0);
else
mergeSort(aux, a, 0, a.length, 0, c);
}

再找到mergeSort方法,

private static void mergeSort(Object[] src,
Object[] dest,
int low,
int high,
int off
                                  Comparator c) 

发现它只有5个参数,那么当sort中c!=null时,c参数是如何影响排序的呢?

(更正)是我看的资料上写错了,少了第六个参数

 Comparator c


-----------------------------------------

我的猜想,c影响了comparable接口,因而影响了mergeSort中含comparable的语句,即我们自定义的comparator规则,替换了compareTo方法,从而在以下语句中体现了出来。

// Merge sorted halves (now in src) into dest
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}