Comparator接口 & Comparable接口

一、Comparable接口

当我们要对数据进行排序时,对于一个简单的数据类型,例如Integer的一个集合:

        List<Integer> integerList = new ArrayList<>();
        integerList.add(3);
        integerList.add(4);
        integerList.add(5);
        integerList.add(1);
        integerList.add(0);
        Collections.sort(integerList);
        System.out.println(integerList);
        /*
			排序结果:
			[0, 1, 3, 4, 5]
		*/

只需要调用 Collections.sort()方法就可以了,而遇到对象进行排序时,就会报错,这是因为Integer类实现了Comparable接口,并且重写了接口中的compareTo(T o)方法,所以程序对于自定义的类对象就无法知道我们需要它如何排序,这个时候我们就让这个类也实现Comparable接口,进而重写方法,完成排序,如下:

/*自定义的类*/
class student implements Comparable<student> {

    int sno;
    int score;

    public student(int sno, int score) {
        this.sno = sno;
        this.score = score;
    }

    @Override
    public int compareTo(student o) {
        if(this.score != o.score) {
            return o.score - this.score;
        } else {
            return this.sno - o.sno;
        }
    }
}

这个时候就可以完成排序了。

二、Comparator接口

打开这个接口的源码一看,有一个注解 @FunctionalInterface , 这说明这是一个函数式接口, 可以使用lamda表达式,而用法的话有了一些变化。

/*自定义排序用法*/
Collections.sort(userList, new Comparator<user>() {
   @Override
   public int compare(user o1, user o2) {
       if(o1.uid != o2.uid) {
           return o1.uid - o2.uid;
       } else {
           return o1.uno - o2.uno;
       }
   }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值