//按照是否有效对list进行排序
Collections.sort(retRights, new Comparator<EstateBaseInfo>() {
@Override
public int compare(EstateBaseInfo o1, EstateBaseInfo o2) {
if(o1.getVaildState()>o2.getVaildState()){
return 1;
}
if(o1.getVaildState()==o2.getVaildState()){
return 0;
}
return -1;
}
});
其中o1代表前一个对象,o2代表后一个对象
如果返回值大于0就将他们互换位置,所以我这里是按照升序排列
反之改为o1.getVaildState()<o2.getVaildState()
将可以按照降序排列了
源码:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set(a[j]);
}
}
可以看出程序首先将
List
转为了Array
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);
}
这里判断是否有自定义的
Comparator
我们需要自定义比较方式
private static void mergeSort(Object[] src,
Object[] dest,
int low, int high, int off,
Comparator c) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i<high; i++)
for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off, c);
mergeSort(dest, src, mid, high, -off, c);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (c.compare(src[mid-1], src[mid]) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
}
private static void swap(Object[] x, int a, int b) {
Object t = x[a];
x[a] = x[b];
x[b] = t;
}
这里是进行排序的主要方法了
可以看出来对于size()<7
的数组直接进行比较运算private static final int INSERTIONSORT_THRESHOLD = 7;
如果前一个指定的值大于后一个的话则直接交换位置