Comparator接口的compare方法
一、原理
当compare(a,b)方法返回值大于0(为true)时,交换a和b
二、分析:
public int compare(Integer o1, Integer o2) {
//元素前 - 元素后 : 升序
//元素后 - 元素前 : 降序
return o2 - o1;
}
元素前 - 元素后 : 升序(从小到大)
元素后 - 元素前 : 降序(从大到小)
1.用法一:compare(a,b) {return a-b;} 表示从小到大排序
假定a>b,(a-b) >0 return true; 交换两者位置,即b<a,即从小到大排序
假定a<b,(a-b) <0 return false; 不交换两者位置,即a<b,即从小到大排序
2.用法二:compare(a,b) {return a-b;} 表示从大到小排序
分析方法同理
三、应用
1.一维数组
2.二维数组
2.1用法一:借助Collections(例中数组对象为抽象类)
public static <T> void sort(List<T> list,Comparator<? super T> ):将集合中元素按照指定规则排序。
Collections.sort(intvls, new SortJobByProc());
新建一个类SortDecrease ,实现Comparator接口,外面调用Collections.sort(待排序数组,new SortDecrease() )
public class SortDecrease implements Comparator {
public int compare(Object jobId1, Object jobId2) {
int id1 = (Integer) jobId1;
int id2 = (Integer) jobId2;
二维数组第三列 后-前:降序排列
return intvls[id2-1][2]-intvls[id1-1][2]
}
}
2.2用法二:比较器匿名内部类写法------(例中数组对象为int)
直接重写,使用判断的方法,intvls是二维数组
Arrays.sort(intvls,new Comparator<int []>(){
@Override
public int compare(int[] o1, int[] o2) {
前-后:升序排序
//二维数组将按第i+1列(即下标为i的列)升序
return o1[i]-o2[i];
}
});
运行实例:
int [][]intvls=new int [3][3];
intvls[0][0]=1; //id
intvls[0][1]=9; //size
intvls[0][2]=19; //time
intvls[1][0]=2;
intvls[1][1]=7;
intvls[1][2]=27; //time
intvls[2][0]=3;
intvls[2][1]=8;
intvls[2][2]=18; //time
Arrays.sort(intvls,new Comparator<int []>(){
@Override
public int compare(int[] o1, int[] o2) {
return o1[1]-o2[1];
}
});
printArry(intvls);
当i=0时,按照第1列排序(原数组)
1 9 19
2 7 27
3 8 18
当i=1时,按照第2列排序
2 7 27
3 8 18
1 9 19
当i=2时,按照第3列排序
3 8 18
1 9 19
2 7 27
其他表达
Arrays.sort(intvls,new Comparator<int []>(){
@Override
public int compare(int[] o1, int[] o2) {
等价于后-前:降序排列
//二维数组将按第i+1列(即下标为i的列)升序
if (o1[2] < o2[2]) {
return 1;
} else {
return 0;
}
}
});
Arrays.sort(intvls,new Comparator<int []>(){
@Override
public int compare(int[] o1, int[] o2) {
后-前:降序排列
//二维数组将按第i+1列(即下标为i的列)升序
return o2[2]-o1[2];
}
});