Java学习--Comparator接口

一、原理

当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];
            }
        });
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值