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);
    }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM