java Comparable和Comparator

在java数组、Collection和Map的排序中,经常会用到Comparable和Comparator这两个接口。

1、Comparable

我们可以通过Arrays.sort()方法给数组排序:

    public static void main(String[] args) {
        int[] intArr={1,5,7,6,3,4};
        Arrays.sort(intArr);
        System.out.println(Arrays.toString(intArr));
        /*
        output:
            [1, 3, 4, 5, 6, 7]
        */
    }

Arrays就是通过将数组中的对象转型为Comparable,再通过compareTo方法进行大小比较的,

如果是我们自定义的类型数组,就需要实现Comparable接口才可以通过这个方法进行排序。

2、Comparator

Comparable的局限也十分明显,当我们需要多种规则进行排序或者倒序排序时,通过Comparable无法实现,但是通过Comparator接口,我们可以很容易解决这个问题。

相比于Comparable是在类的内部实现,Comparator是在外部实现,不对原类造成任何影响,所以灵活许多。

例如,有一学生信息List,我们根据其分数从高到第进行排序:

public class Student {

    public int score;

    public Student(int score) {
        this.score = score;
    }

}
    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>();
        students.add(new Student(70));
        students.add(new Student(60));
        students.add(new Student(90));
        students.add(new Student(80));
        Collections.sort(students, new Comparator<Student>() {

            @Override
            public int compare(Student o1, Student o2) {
                // TODO Auto-generated method stub
                return o2.score - o1.score;
            }
        });
        for (Student student : students) {
            System.out.println(student.score);
        }
    }

输出:

90
80
70
60

  

posted @ 2016-04-02 20:39  maozs  阅读(211)  评论(0编辑  收藏  举报