前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Comparator(用于Collections.sort())

Comparator(用于Collections.sort())

作者头像
用户9854323
发布2022-06-25 09:57:23
1610
发布2022-06-25 09:57:23
举报
文章被收录于专栏:小陈飞砖

Comparator在jdk7前是megesort,jdk7之后是Timsort,看下面连接 http://blog.sina.com.cn/s/blog_8e6f1b330101h7fa.html

代码语言:javascript
复制
package Text;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Text {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<Integer>();
        a.add(5);
        a.add(7);
        a.add(4);
        Collections.sort(a, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                System.out.println(a+"比"+b);
                return a - b;
            }
        });
        System.out.println(a);
    }
}

输出:

代码语言:javascript
复制
7比5
4比7
4比7
4比5
[4, 5, 7]

当把return b-a时:

代码语言:javascript
复制
package Text;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Text {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<Integer>();
        a.add(5);
        a.add(7);
        a.add(4);
        Collections.sort(a, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                System.out.println(a+"比"+b);
                return b - a;
            }
        });
        System.out.println(a);
    }
}

输出:

代码语言:javascript
复制
7比5
4比7
4比5
[7, 5, 4]

总结: 升序:a-b 降序:b-a 也可以 升序用 return a>=b?1:-1; 降序用:return a>=b?-1:1;

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-07-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档