TengFei'sBlog

从点滴做起,每天都要有提升。

Java开发小知识点总结

1 Comparable和Comparator的区别(参考自温布利往事

Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays.sort进行自动排序,此外,实现此接口的对象可以用作有序映射中的键或有序集合中的集合,无需指定比较器。
Comparator是比较接口,我们如果需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口),那么我们就可以建立一个“该类的比较器”来进行排序,这个“比较器”只需要实现Comparator接口即可。也就是说,我们可以通过实现Comparator来新建一个比较器,然后通过这个比较器对类进行排序。

public class People implements Comparable<People> {
    private String name;
    private int age;

    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(People people) {

        return this.age - people.age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
//针对age进行正序排序
        People people0 = new People("TengFei", 23);
        People people1 = new People("WangBing", 34);
        People people2 = new People("AHao", 13);
        List<People> peopleList = new ArrayList<>();
        peopleList.add(people0);
        peopleList.add(people1);
        peopleList.add(people2);
        Collections.sort(peopleList);
        for (People people : peopleList){
            System.out.println(people.getAge());
        }
//将name按字典顺序排序
        People people0 = new People("TengFei", 23);
        People people1 = new People("WangBing", 34);
        People people2 = new People("AHao", 13);
        List<People> peopleList = new ArrayList<>();
        peopleList.add(people0);
        peopleList.add(people1);
        peopleList.add(people2);
        Collections.sort(peopleList, new Comparator<People>() {
            @Override
            public int compare(People first, People second) {
                return first.getName().compareTo(second.getName());
            }
        });
        for (People people : peopleList){
            System.out.println(people.getName());
        }
    }
阅读更多
文章标签: Java
个人分类: Java
上一篇IPC机制之AIDL
想对作者说点什么? 我来说一句

java开发总结

2017年10月06日 33KB 下载

没有更多推荐了,返回首页

关闭
关闭