comparator和comparable的区别

Comparable  java.lang  内比较器

传入一个对象,与自身进行比较,返回差值 正整数 0 负整数。

实现接口 :public interface Comparable<T>

接口定义的方法:public int compareTo(T o);

举例:

    private static  class Student implements Comparable{
        int id;

        private Student(int id){
            this.id = id;
        }

        @Override
        public int compareTo(Object o) {
            return this.id - ((Student)o).id;
        }
    }
    public void studentCompareTo(){
        Student s1 = new Student(10);
        Student s2 = new Student(20);

        int b = s1.compareTo(s2);
        System.out.println(String.valueOf(b));
    }

 

Comparator  java.util 外比较器

传入两个对象,进行比较

实现接口:public interface Comparator<T> 

接口定义的方法  int compare(T o1, T o2);

举例

   private static class StudentCom1 implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.id - o2.id;
        }
    }

    public void studentCompatator() {
        List<Student> students = new ArrayList<>();
        Student student1 = new Student(10);
        students.add(student1);
        Student student2 = new Student(20);
        students.add(student2);
        Student student3 = new Student(15);
        students.add(student3);

        Collections.sort(students, new StudentCom1());
        for (Student student : students)
            System.out.println(student.id);
    }